繁体   English   中英

ContextStartedEvent未在自定义侦听器中触发

[英]ContextStartedEvent not firing in custom listener

我正在尝试使用这样的自定义应用程序侦听器来创建上下文

@Component
public class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {

    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println("Context started"); // this never happens
    }
}

但是onApplicationEvent方法永远不会触发。 如果我使用诸如ContextRefreshedEvent类的其他事件,则它可以正常工作,但是在创建它之前,我需要先进行了解。 有什么建议吗? 谢谢!

[编辑]

编辑表决由于投票不足而添加了更多信息。

之所以没有通过侦听器进行回调,是因为您没有显式调用LifeCycle start()方法( JavaDoc )。

这通常在Spring Boot情况下通过ConfigurableApplicationContext通过AbstractApplicationContext层叠到您的ApplicationContext

下面的工作代码示例演示了回调的工作方式(只需显式调用start()方法)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        applicationContext.start();
    }

    @Component
    class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {

        @Override
        public void onApplicationEvent(ContextStartedEvent event) {
            System.out.println("Context started");
        }
    }
}

我之所以在ContextRefreshedEvent回调下面建议的原因是,在后台调用了refresh()代码。

如果您深入研究SpringApplication#run()方法,最终将看到它

再次这是一个使用ContextRefreshedEvent的工作示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Component
    class ContextStartedListener implements ApplicationListener<ContextRefreshedEvent> {

        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            System.out.println("Context refreshed");
        }
    }
}

[编辑前]

将通用类型改为ContextRefreshedEvent ,然后它应该可以工作。

有关更多详细信息,请阅读Spring Blog中的这篇文章 仅引用有关ContextRefreshedEvent的部分:

[..]这使MyListener可以在上下文刷新时得到通知,并且可以在应用程序上下文完全启动时使用它来运行任意代码。[..]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM