java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring监听器

Spring ApplicationListener监听器用法详解

作者:闻窗

这篇文章主要介绍了Spring ApplicationListener监听器用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了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容器在创建实例化销毁的过程中的发布事件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文