代码之家  ›  专栏  ›  技术社区  ›  secondbreakfast

自定义侦听器中未触发ContextStartedEvent

  •  9
  • secondbreakfast  · 技术社区  · 7 年前

    我正在尝试使用如下自定义应用程序侦听器连接到上下文的创建中

    @Component
    public class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {
    
        @Override
        public void onApplicationEvent(ContextStartedEvent event) {
            System.out.println("Context started"); // this never happens
        }
    }
    

    但是 onApplicationEvent 方法从不激发。如果我使用不同的事件,例如 ContextRefreshedEvent 然后它工作得很好,但我需要在创建它之前将其钩住。有什么建议吗?谢谢

    1 回复  |  直到 7 年前
        1
  •  18
  •   dimitrisli    7 年前

    [编辑]

    编辑答案添加更多信息,因为否决票。

    您没有收到侦听器的回调的原因是,您没有显式调用 生命周期 start() 方法( JavaDoc ).

    这将级联到您的 应用程序上下文 通常通过 AbstractApplicationContext 在弹簧防尘套中通过 配置应用程序上下文 .

    下面的工作代码示例演示了回调的工作方式(只需显式调用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() 方法 you'll eventually see it .

    这里还有一个工作示例,说明如何使用 上下文刷新事件 :

    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");
            }
        }
    }
    

    [编辑前]

    将泛型类型更改为 上下文刷新事件 相反,它应该会起作用。

    有关更多详细信息,请阅读 this article from the Spring Blog . 仅引用有关 上下文刷新事件 :

    [..]这样,当上下文 已刷新 当应用程序 上下文已完全启动。[..]