-
spring boot - 전체 초기화 코드를 넣어보자기록해야 기억한다/Spring 2020. 11. 14. 22:10
spring boot 에서는 몇가지 초기화 방법이 있다. 사용하는 사람마다 선호하는 방법이 있을테니 그것대로 사용하면 되지만 각 방법의 목적과 사용방법에 대해 정리한다.
CommandLineRunner 인터페이스 사용
@FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; }
1.0.0 버전부터 정의된 것처럼 @FunctionalInterface 이며 해당 인터페이스를 통해 선언된 Bean 이 SpringApplication 내에 포함이 될 때 실행되어야 함을 나타내는데 사용되는 인터페이스이다. 여러 Bean 을 동일한 ApplicationContext 내에서 정의 할 수 있으며 이 때는 Ordered 인터페이스 또는 @Order 를 사용하여 순서를 지정할 수 있다.
만약 파라미터에 문자열 배열 대신 ApplicationArguments 에 접근할 필요가 있는 경우는 ApplicationRunner 를 사용하는 것이 좋다.
@Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 초기화 작업 수행 } }
ApplicationRunner 인터페이스 사용
1.3.0 에 추가된 인터페이스이고 해당 인터페이스는 String[] 대신에 ApplicationArguments 를 args 로 받아서 실행한다. CommandLineRunner 와 마찬가지로 여러 Bean 으로 정의할 수 있고 Ordered 를 통해 순서를 지정할 수 있다.
@FunctionalInterface public interface ApplicationRunner { void run(ApplicationArguments args) throws Exception; }
ApplicationArguments 는 SpringApplication 을 실행하는데 사용된 인수에 대한 액세스를 제공하는 인터페이스이다.
ApplicationEvent 클래스 사용
spring 은 spring-context 에서 추상화된 ApplicationEvent 를 통해 많은 작업들을 할 수 있고, 대부분 별로 사용하지 않고 있지만 알고 있으면 강력한 기능이 될 수 있으며 Application 의 초기화 작업에도 이를 이용할 수 있다. spring boot 에서는 ApplicationEvent 를 상속한 SpringApplicationEvent 라는 클래스를 추상화하였으며 이는 또 다시 여러개의 Event 형태별로 구현되어 있다.
클래스 명 설명 ApplicationContextInitializedEvent ApplicationContext 가 준비되고 Bean 정의가 로드되기 전에 생기는 이벤트 ApplicationEnvironmentPreparedEvent Application 이 시작되고 Environment 가 처음으로 준비될 때 생기는 이벤트 ApplicationPreparedEvent Application 이 시작되고 ApplicationContext 가 완전히 준비되었지만 refresh 가 되지 않았을 때 생기는 이벤트. Bean 정의가 로드되고 Environment 는 이 단계에서 준비된다. ApplicationStartedEvent ApplicationContext 가 refresh 가 되고 Application 이나 command line runner가 호출되기 전에 생기는 이벤트 ApplicationReadyEvent Application 이 서비스를 위한 request 를 처리 할 준비가 되었음을 나타 내기 위해 가능한 한 늦게 생기는 이벤트. 이벤트의 소스는 SpringApplication 자체이지만 모든 초기화 단계는 그때까지 완료 될 것이므로 내부 상태를 수정하지 않도록 주의해야한다. ApplicationFailedEvent 시작시 실패할 경우에 생기는 이벤트 ApplicationStartingEvent SpringApplication 이 시작되자마자 가능한 한 빨리 이벤트가 생성됨.(Environment 또는 ApplicationContext를 사용할 수 있기 전이지만 ApplicationListeners가 등록 된 후) 이벤트의 소스는 SpringApplication 자체이지만 라이프 사이클에서 나중에 수정 될 수 있으므로 초기 단계에서 내부 상태를 너무 많이 사용하지 않도록 주의하여야 한다. Event 의 정의에 따라 Runner 와 비슷하게 여러가지의 Event 에 대해서 사용할 수 있고, 초기화하는 내용에 따라 적절한 ApplicationEvent 를 선택하여 적용하면 된다.
@Component public class StartingEventComponent implements ApplicationListener<ApplicationStartingEvent> { @Override public void onApplicationEvent(ApplicationStartingEvent event) { // 초기화 작업.. // event.getArgs(); } }
ApplicationEvent 의 내용은 별도의 글로 다시 정리할 예정이다.
반응형LIST'기록해야 기억한다 > Spring' 카테고리의 다른 글
Spring REST 에서의 Global Exception (0) 2021.01.11 Spring Cloud OpenFeign, 그리고 SSL (2) 2020.12.29 스케줄러에 property 주입하기 (0) 2020.12.17 Spring Boot 의 properties (0) 2020.11.16 Spring Boot 분석(구동 원리) (0) 2020.11.14