春季:初始化应用后如何启动逻辑

时间:2020-06-02 20:08:35

标签: java spring

我已经实现了这种逻辑

@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,但据我了解,它可以多次调用

2 个答案:

答案 0 :(得分:0)

您可以注释@DependsOn,这可以强制Spring容器在使用@DependsOn注释进行注释的bean之前初始化一个或多个bean。 然后,您将确定SomeClass将在SomeUpdater之前初始化。

长期解决方案是:

  1. Spring Boot启动挂钩
  2. Spring事件类型,例如ApplicationStartedEvent,ApplicationReadyEvent。

有用的链接: 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));
    });
}