当前位置: 移动技术网 > IT编程>开发语言>Java > Spring ApplicationListener的使用详解

Spring ApplicationListener的使用详解

2020年06月23日  | 移动技术网IT编程  | 我要评论

介绍

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 内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网