복붙노트

[SPRING] 스프링 부트가 시작된 후 코드 실행하기

SPRING

스프링 부트가 시작된 후 코드 실행하기

내 봄 부팅 애플 리케이션 변경 사항에 대한 디렉토리를 모니터링하기 시작하면 코드를 실행하고 싶습니다.

새로운 스레드를 실행하려고 시도했지만 그 시점에서 @Autowired 서비스가 설정되지 않았습니다.

@Autowired 주석이 설정되기 전에 실행되는 ApplicationPreparedEvent를 찾을 수있었습니다. 응용 프로그램이 HTTP 요청을 처리 할 준비가되면 이상적으로 이벤트를 발생시키고 싶습니다.

응용 프로그램을 봄 부팅으로 사용하면 더 나은 이벤트를 사용할 수 있습니까? 아니면 코드를 실행하는 좋은 방법이 있습니까?

해결법

  1. ==============================

    1.시험:

    시험:

    @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    public class Application extends SpringBootServletInitializer {
    
        @SuppressWarnings("resource")
        public static void main(final String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    
            context.getBean(Table.class).fillWithTestdata(); // <-- here
        }
    }
    
  2. ==============================

    2.다음과 같이 간단합니다.

    다음과 같이 간단합니다.

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        System.out.println("hello world, I have just started up");
    }
    

    버전 1.5.1에서 테스트되었습니다. 릴리스

  3. ==============================

    3.초기화시 모니터를 시작하는 bean을 생성하는 것만 큼은 아닙니다 :

    초기화시 모니터를 시작하는 bean을 생성하는 것만 큼은 아닙니다 :

    @Component
    public class Monitor {
        @Autowired private SomeService service
    
        @PostConstruct
        public void init(){
            // start your monitoring in here
        }
    }
    

    init 메소드는 bean에 대한 autowiring이 완료 될 때까지 호출되지 않습니다.

  4. ==============================

    4.ApplicationReadyEvent를 사용해 보셨습니까?

    ApplicationReadyEvent를 사용해 보셨습니까?

    @Component
    public class ApplicationStartup 
    implements ApplicationListener<ApplicationReadyEvent> {
    
      /**
       * This event is executed as late as conceivably possible to indicate that 
       * the application is ready to service requests.
       */
      @Override
      public void onApplicationEvent(final ApplicationReadyEvent event) {
    
        // here your code ...
    
        return;
      }
    }
    

    코드 : http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

    다음은 시작 이벤트에 대한 설명서입니다.

  5. ==============================

    5."Spring Boot"방법은 CommandLineRunner를 사용하는 것입니다. 그 유형의 콩을 추가하면 잘 갈 수 있습니다. Spring 4.1 (Boot 1.2)에는 모든 것이 초기화 된 후에 콜백을 얻는 SmartInitializingBean도있다. 또한 SmartLifecycle (Spring 3부터)이 있습니다.

    "Spring Boot"방법은 CommandLineRunner를 사용하는 것입니다. 그 유형의 콩을 추가하면 잘 갈 수 있습니다. Spring 4.1 (Boot 1.2)에는 모든 것이 초기화 된 후에 콜백을 얻는 SmartInitializingBean도있다. 또한 SmartLifecycle (Spring 3부터)이 있습니다.

  6. ==============================

    6.ApplicationRunner를 사용하여 클래스를 확장하고 run () 메서드를 재정의 한 다음 코드를 추가 할 수 있습니다.

    ApplicationRunner를 사용하여 클래스를 확장하고 run () 메서드를 재정의 한 다음 코드를 추가 할 수 있습니다.

    import org.springframework.boot.ApplicationRunner;
    
    @Component
    public class ServerInitializer implements ApplicationRunner {
    
        @Override
        public void run(ApplicationArguments applicationArguments) throws Exception {
    
            //code goes here
    
        }
    }
    
  7. ==============================

    7.스프링 구성 :

    스프링 구성 :

    @Configuration
    public class ProjectConfiguration {
        private static final Logger log = 
       LoggerFactory.getLogger(ProjectConfiguration.class);
    
       @EventListener(ApplicationReadyEvent.class)
       public void doSomethingAfterStartup() {
        log.info("hello world, I have just started up");
      }
    }
    
  8. ==============================

    8.ApplicationReadyEvent는 실제로 수행하려는 태스크가 올바른 서버 조작에 대한 요구 사항이 아닌 경우에만 유용합니다. 변경 사항을 모니터하기 위해 비동기 태스크를 시작하는 것이 좋은 예입니다.

    ApplicationReadyEvent는 실제로 수행하려는 태스크가 올바른 서버 조작에 대한 요구 사항이 아닌 경우에만 유용합니다. 변경 사항을 모니터하기 위해 비동기 태스크를 시작하는 것이 좋은 예입니다.

    그러나 서버가 작업이 완료 될 때까지 '준비 상태가 아님'상태 인 경우 SmartInitializingSingleton을 구현하는 것이 좋습니다. REST 포트가 열리고 서버가 비즈니스에 열려 있기 전에 콜백을받을 것이기 때문입니다.

    한 번만 발생해야하는 작업에 @PostConstruct를 사용하도록 유혹하지 마십시오. 여러 번 호출되는 것을 발견하면 무례한 놀라움을 느낄 것입니다 ...

  9. ==============================

    9.Spring> 4.1에서 SmartInitializingSingleton 빈을 사용하라.

    Spring> 4.1에서 SmartInitializingSingleton 빈을 사용하라.

    @Bean
    public SmartInitializingSingleton importProcessor() {
        return () -> {
            doStuff();
        };
    
    }
    

    대신 CommandLineRunner bean을 구현하거나 @PostConstruct로 bean 메소드에 주석을 달 수 있습니다.

  10. ==============================

    10.매력처럼 작동하는 Dave Syer의 대답에 대한 예를 제공합니다.

    매력처럼 작동하는 Dave Syer의 대답에 대한 예를 제공합니다.

    @Component
    public class CommandLineAppStartupRunner implements CommandLineRunner {
        private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
    
        @Override
        public void run(String...args) throws Exception {
            logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
        }
    }
    
  11. ==============================

    11.스프링 부팅 응용 프로그램 용 CommandLineRunner를 구현하십시오. 당신은 run 메소드를 구현할 필요가있다.

    스프링 부팅 응용 프로그램 용 CommandLineRunner를 구현하십시오. 당신은 run 메소드를 구현할 필요가있다.

    public classs SpringBootApplication implements CommandLineRunner{
    
        @Override
            public void run(String... arg0) throws Exception {
            // write your logic here 
    
            }
    }
    
  12. ==============================

    12.이것을 시도하면 응용 프로그램 컨텍스트가 완전히 시작되면 코드가 실행됩니다.

    이것을 시도하면 응용 프로그램 컨텍스트가 완전히 시작되면 코드가 실행됩니다.

     @Component
    public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent arg0) {
                    // EXECUTE YOUR CODE HERE 
        }
    }
    
  13. from https://stackoverflow.com/questions/27405713/running-code-after-spring-boot-starts by cc-by-sa and MIT license