欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring ApplicationListener的使用详解

程序员文章站 2023-10-28 07:58:39
介绍spring applicationlistener 是spring事件机制的一部分,与applicationevent抽象类结合完成applicationcontext的事件通知机制.conte...

介绍

spring applicationlistener 是spring事件机制的一部分,与applicationevent抽象类结合完成applicationcontext的事件通知机制.

contextrefreshedevent事件监听

以spring的内置事件contextrefreshedevent为例,当applicationcontext被初始化或刷新时,会触发contextrefreshedevent事件.如下代码示例:

@component
public class learnlistener implements applicationlistener<contextrefreshedevent> {
  @override
  public void onapplicationevent(contextrefreshedevent event) {
   //获取所有的bean
   string[] definitionnames = event.getapplicationcontext().getbeandefinitionnames();
   for (string name : definitionnames) {
     //打印名称
     system.out.println("name = " + name);
   }
  }
}

自定义事件

代码

//继承applicationevent 抽象类就可以自定义事件模型
public class myevent extends applicationevent {
 
  private long id;
  private string message;
  public myevent(object source) {
    super(source);
  }

  public myevent(object source, long id, string message) {
    super(source);
    this.id = id;
    this.message = message;
  }
  //get set 方法省略
}

//实现applicationlistener接口
  @component
public class mylistener implements applicationlistener<myevent> {
  @override
  public void onapplicationevent(myevent event) {
    system.out.println("监听到事件: "+event.getid()+"\t"+event.getmessage());
  }
}

测试

@springboottest
@runwith(springrunner.class)
public class listenertest {
  @autowired
  private applicationcontext applicationcontext;

  @test
  public void testlistenner() {
    myevent myevent = new myevent("myevent", 9527l, "十二点了 该吃饭了~");
    applicationcontext.publishevent(myevent);
   // system.out.println("发送结束");
  }
}

结果

Spring ApplicationListener的使用详解

到此这篇关于spring applicationlistener的使用详解的文章就介绍到这了,更多相关spring applicationlistener 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!