spring中的ApplicationListener监听器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring中的ApplicationListener监听器相关的知识,希望对你有一定的参考价值。

监听器在使用过程中可以监听到某一事件的发生,进而对事件做出相应的处理。

首先自定义一个监听器myListener实现ApplicationListener接口

@Repository
public class myListener implements ApplicationListener<ApplicationEvent>{
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("监听到的事件发布。。。。。。。。。。"+event.getClass());
        System.out.println("监听的内容。。。。。。。。。。"+event.toString());
    }
}

创建配置类MainListenerConfig:将myListener组件加入到容器中

@Configuration
@Import(myListener.class)
public class MainListenerConfig {

}

测试

  public class ListenerTest {

    @Test
    public void  test(){
        //创建容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainListenerConfig.class);
        applicationContext.publishEvent(new ApplicationEvent("我发布的事件") {});
        applicationContext.close();
    }
}

 

 打印输出:可以监听到自己发布的事件和spring容器在创建实例化销毁的过程中的发布事件。

以上是关于spring中的ApplicationListener监听器的主要内容,如果未能解决你的问题,请参考以下文章