我已经实现了这种逻辑
@Component
public class SomeUpdater {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
private ExecutorService executorService;
@PostConstruct
public void init(){
executorService = Executors.newSingleThreadExecutor();
executorService.execute(()->{
//some logic
applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
});
}
}
@Component
public class SomeClass {
@EventListener
public void update(PurposeEvent purposeEvent){
//update
}
}
但是我从日志中看到,update (PurposeEvent purposeEvent)
的侦听器在调用方法applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
之后被初始化。初始化后如何调用逻辑?我尝试将@EventListener
用于ContextRefreshedEvent
,但据我了解,它可以多次调用
答案 0 :(得分:0)
您可以注释@DependsOn,这可以强制Spring容器在使用@DependsOn注释进行注释的bean之前初始化一个或多个bean。 然后,您将确定SomeClass将在SomeUpdater之前初始化。
长期解决方案是:
有用的链接: http://dolszewski.com/spring/running-code-on-spring-boot-startup/ http://javainfinite.com/spring-boot/springboot-applicationreadyevent-applicationfailedevent-contextrefreshedevent/
答案 1 :(得分:0)
您可以利用如下所示的春季活动,
@EventListener(ApplicationReadyEvent.class)
public void init() {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
//some logic
applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
});
}