Develop/Spring
[Spring] Spring boot 구동 시 특정 코드 실행하는 방법
코딩의성지
2020. 5. 15. 00:21
하이 ~~!!
Spring 으로 어떤 서비스를 올리다보면 구동시 바로 실행이 되었으면 하는 코드들이 있을거다.
그걸 할수 있는 방법을 소개해드리겠다.
스프링부트에서는 어플리케이션이 구동될 때 코드를 실행시키는 2가지 방법을 제공한다.
CommandLineRunner 와 ApplicationRunner 인데 바로 예를들어 보여드리겠다.
1. CommandLineRunner
1
2
3
4
5
6
7
8
9
10
11
|
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("1.command line runner");
}
}
|
이 코드를 작성하고 jar를 구동해보면 아래와 같은 결과가 나온다.
![](https://blog.kakaocdn.net/dn/bwvaPD/btqEa08R58d/NOkfyEPgzswe6NHbxABFv0/img.png)
2.ApplicationRunner
1
2
3
4
5
6
7
8
9
10
11
12
|
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("2.application runner");
}
}
|
이 코드 역시 구동해보면 아래의 결과를 확인해볼 수 있다.
![](https://blog.kakaocdn.net/dn/cvHHef/btqEa08SbLB/GsNvuWGLQ8wj2oHp31gv3k/img.png)
그럼 .. 두가지 인터페이스의 차이점은 무엇일까? 다들 코드를 보시면 아시겠지만 바로 파라미터이다.
CommandLineRunner의 경우 스트링 배열이 파라미터로 들어오지만 ApplicationRunner의 경우 스트링 배열을 포함한 더 많은 데이터를 받아 올 수 있는 ApplicationArguments 타입의 객체가 파라미터로 넘어온다.
아..! 그리고 마지막으로 이거 하나만 알아두자..!
이 Runner 의 경우 여러 개가 있어도 된다. 그런데 .. 여러개가 있으면 그 순서를 정해줘야하지 않겠는가!
순서를 정해주는 방법은 @Order Annotation을 이용해주면 된다.
@Order(1)
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Order(2)
@Component
public class TestApplicationRunner implements ApplicationRunner {
이 코드 역시 작성해놓고 jar를 구동해보면 ..!
이렇게 순서를 정해준대로 결과가 나오는 것을 확인할 수 있다.
그럼 다들 필요하시면 이 코드 잘 응용해서 사용하시길 바란다. 즐거운 코딩하자~~
반응형