Spring ApplicationListener的使用详解

网友投稿 303 2023-05-26

Spring ApplicationListener的使用详解

介绍

Spring ApfinJMsIplicationListener 是Spring事件机制的一部分,与ApplicationEvent抽象类结合完成ApplicationContext的事件通知机制.

ContextRefreshedEvent事件监听

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

@Component

public class LearnListener implements ApplicationListener {

@Override

public void onApplicationEvent(ContextRefreshedEvent event) {

//获取所有的bean

String[] definitionNames = event.getApplicationContext().getBeanDefinitionNames();

for (StrinfinJMsIg 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 {

@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("发送结束");

}

}

结果

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:践行数字化转型——探索地方政府数字政务的网络基础组建
下一篇:Java圆柱体表面积和体积计算代码实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~