久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Spring ApplicationListener的使用詳解

瀏覽:4日期:2023-09-03 14:27:45

介紹

Spring ApplicationListener 是Spring事件機(jī)制的一部分,與ApplicationEvent抽象類結(jié)合完成ApplicationContext的事件通知機(jī)制.

ContextRefreshedEvent事件監(jiān)聽

以Spring的內(nèi)置事件ContextRefreshedEvent為例,當(dāng)ApplicationContext被初始化或刷新時,會觸發(fā)ContextRefreshedEvent事件.如下代碼示例:

@Componentpublic 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 方法省略}

//實(shí)現(xiàn)ApplicationListener接口 @Componentpublic class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { System.out.println('監(jiān)聽到事件: '+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, '十二點(diǎn)了 該吃飯了~'); applicationContext.publishEvent(myEvent); // System.out.println('發(fā)送結(jié)束'); }}

結(jié)果

Spring ApplicationListener的使用詳解

到此這篇關(guān)于Spring ApplicationListener的使用詳解的文章就介紹到這了,更多相關(guān)Spring ApplicationListener 內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 宜城市| 宝山区| 翁牛特旗| 内江市| 祁门县| 锡林浩特市| 牙克石市| 黔南| 昔阳县| 惠来县| 清远市| 沭阳县| 临武县| 庆阳市| 浦县| 宣城市| 东乡县| 太仓市| 哈巴河县| 石棉县| 鄱阳县| 子洲县| 景洪市| 额尔古纳市| 蒲江县| 定日县| 霍城县| 阜城县| 阿拉善左旗| 天长市| 巨野县| 无为县| 阿城市| 堆龙德庆县| 山东| 定州市| 杂多县| 常德市| 钟祥市| 基隆市| 韶关市|