스프링 부트 앱이 디렉토리 변경 사항을 모니터링하기 시작한 후에 코드를 실행하고 싶습니다 .
새 스레드를 실행하려고 시도했지만 @Autowired
해당 시점에 서비스가 설정되지 않았습니다.
주석을 설정 ApplicationPreparedEvent
하기 전에 시작되는를 찾을 수있었습니다 @Autowired
. 이상적으로 응용 프로그램이 http 요청을 처리 할 준비가되면 이벤트를 시작하고 싶습니다.
사용하기에 더 좋은 이벤트가 있습니까, 아니면 응용 프로그램이 스프링 부트 에 들어간 후에 더 나은 코드 실행 방법이 있습니까?
답변
시험:
@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
}
}
답변
다음과 같이 간단합니다.
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println("hello world, I have just started up");
}
버전에서 테스트 1.5.1.RELEASE
답변
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/
다음은 시작 이벤트에 대한 설명서입니다 .
…
응용 프로그램 이벤트는 응용 프로그램이 실행될 때 다음 순서로 전송됩니다.
ApplicationStartedEvent는 실행 시작시 리스너 및 이니셜 라이저 등록을 제외한 처리 전에 전송됩니다.
ApplicationEnvironmentPreparedEvent는 컨텍스트에서 사용될 환경이 알려져있을 때, 그러나 컨텍스트가 작성되기 전에 전송됩니다.
ApplicationPreparedEvent는 새로 고침이 시작되기 직전이지만 Bean 정의가로드 된 후에 전송됩니다.
새로 고친 후 ApplicationReadyEvent가 전송되고 관련 콜백이 처리되어 응용 프로그램이 요청을 처리 할 준비가되었음을 나타냅니다.
시작할 때 예외가 있으면 ApplicationFailedEvent가 전송됩니다.
…
답변
초기화시 모니터를 시작하는 Bean을 작성하지 마십시오.
@Component
public class Monitor {
@Autowired private SomeService service
@PostConstruct
public void init(){
// start your monitoring in here
}
}
init
어떤에서 autowiring이 콩에 대한 완료 될 때까지 메서드가 호출되지 않습니다.
답변
“Spring Boot”방법은을 사용하는 것 CommandLineRunner
입니다. 해당 유형의 콩을 추가하면 좋습니다. Spring 4.1 (Boot 1.2)에는 SmartInitializingBean
모든 것이 초기화 된 후 콜백이 발생합니다. 그리고 SmartLifecycle
(봄 3부터) 있습니다.
답변
를 사용하여 클래스를 확장 ApplicationRunner
하고 run()
메서드를 재정의 하고 코드를 추가 할 수 있습니다.
import org.springframework.boot.ApplicationRunner;
@Component
public class ServerInitializer implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
//code goes here
}
}
답변
ApplicationReadyEvent
수행하려는 작업이 올바른 서버 작업에 필요하지 않은 경우에만 유용합니다. 변경 사항을 모니터링하기 위해 비동기 작업을 시작하는 것이 좋은 예입니다.
그러나 작업이 완료 될 때까지 서버가 ‘준비되지 않음’상태 인 경우 REST 포트가 열리고 서버가 비즈니스 용으로 열리기 전에SmartInitializingSingleton
콜백을 받기 때문에 구현하는 것이 좋습니다 .
@PostConstruct
한 번만 발생해야하는 작업 에 사용하려는 유혹을받지 마십시오 . 여러 번 호출되는 것을 발견하면 무례한 놀라움을 느낄 것입니다 …