ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [spring] spring boot 초기 구동 시키기 및 초기화 코드
    Spring/spring boot 및 기타 2020. 8. 29. 16:34

    스프링 어플리케이션을 시작할때 어플리케이션이 뜰때 초기 구동시켜줘야하는 코드들이 있을 수 있다.

    이 때 해결 방법이

    CommandLineRunner, ApplicationRunner, @EventListener  방법으로 초기 실행코드를 구현 할 수 있다.

     

    @Component //component scanning에 의한 방식으로 빈을 등록하는 방법 
    public class MyCLRunner implements CommandLineRunner {
    
    	@Override 
        public void run(String... args) throws Exception { 
       		System.out.println("CommandLineRunner Args: " + Arrays.toString(args));
        } 
    }
    

    또는 @Bean 으로 사용 가능 

    @Bean 
    public CommandLineRunner myCLRunner() { 
    	return args -> System.out.println("Hello Lambda CommandLineRunner!!"); 
    }
    

     

    구동시 파라미터를 다음과 같이 받을 수 있다. 아래 방식은 ApplicationRunner 도 동일하다.

    $ java -jar target/demo-0.0.1-SNAPSHOT.jar abc 123

    2. ApplicationRunner 

    CommandLineRunner 와 사용법은 똑같지만 다른 것은 파라미터 타입이 다른것 뿐이다.

    ApplicationRunner 가 더 최근에 나온 방식이다.

    @Component
    public class DemoApplicationRunner implements ApplicationRunner {
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("ApplicationRunner Args: " + Arrays.toString(args.getSourceArgs()));
        }
    
    }
    @Bean 
    public ApplicationRunner myApplicationRunner() { 
    	return args -> System.out.println("Hello ApplicationRunner"); 
    }
    

     

     

    ApplicationRunner가 CommandLineRunner보다 일찍 실행된다.

    다음과 같이 만든 초기구동 컴포넌트들이 실행순서가 이슈가 있을 경우 순서를 지정할 수 있다,

    @Order(1)
    @Component
    public class DemoCommandLineRunner implements CommandLineRunner { ...
    
    @Order(2)
    @Component
    public class DemoApplicationRunner implements ApplicationRunner { ...

    3. @EventListener

    이벤트 리스너가 최근에 나온 방식(4.2 이후)으로 이벤트를 연결해 초기 구동시 해당 클래스를 실행시킬 수 있다.

    @SpringBootApplication public class SpringinitApplication { 
    	public static void main(String[] args) { //ConfigurableApplicationContext : ApplicationContext를 코드에 의해서 재구성할 수 있도록 기능을 집어넣은 ApplicationContext. 
          ConfigurableApplicationContext ac = SpringApplication.run(SpringinitApplication.class, args); 
          ac.publishEvent(new MyEvent(ac,"My Spring Event")); 
        } 
        
        @EventListener(MyEvent.class) 
        public void onMyEvent(MyEvent myEvent){ 
        	System.out.println("Hello EventListener : " + myEvent.getMessage()); 
        } 
        static class MyEvent extends ApplicationEvent { 
       		private final String message; //원래 String message는 없는 건데 추가한 것임. 
            public MyEvent(Object source, String message) { 
            	super(source); this.message = message; 
      		} 
            public String getMessage(){ 
            	return message; 
            } 
        } 
    }
    

     

    여러개 클래스의 경우 다음과 같이 실행할 수 있다.

    @EvnetListener({MyEvent.class, ApplicationReadyEvent.class})

    참고문헌https://www.daleseo.com/spring-boot-runners/ [스프링 부트 구동 시점에 특정 코드 실행 시키기] 
    https://jeong-pro.tistory.com/206[스프링 부트 애플리케이션에서 초기화 코드 3가지 방법]

    반응형

    댓글

Designed by Tistory.