Spring ApplicationListener监听器用法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring ApplicationListener监听器用法详解

  2021-04-02 我要评论

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

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们