国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Spring ApplicationListener的使用詳解

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

介紹

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

ContextRefreshedEvent事件監聽

以Spring的內置事件ContextRefreshedEvent為例,當ApplicationContext被初始化或刷新時,會觸發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 方法省略}

//實現ApplicationListener接口 @Componentpublic 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 內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 饶阳县| 光山县| 吴旗县| 十堰市| 阿克陶县| 通榆县| 东安县| 海林市| 怀安县| 连云港市| 昆明市| 深泽县| 运城市| 多伦县| 哈密市| 台东县| 宁晋县| 越西县| 汝南县| 六枝特区| 江西省| 渝中区| 景洪市| 高邮市| 怀安县| 瑞金市| 蓬莱市| 余庆县| 元氏县| 天津市| 平昌县| 万年县| 宁夏| 邯郸县| 竹溪县| 瑞安市| 广昌县| 东海县| 竹北市| 乡城县| 启东市|