當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot ApplicationListener监听器的使用-监听ApplicationReadyEvent事件
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot ApplicationListener监听器的使用-监听ApplicationReadyEvent事件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
SpringBoot監(jiān)聽器
ApplicationContext事件機制是觀察者設計模式的實現(xiàn),通過ApplicationEvent類和ApplicationListener接口,可以實現(xiàn)ApplicationContext事件處理。
如果容器中有一個ApplicationListener Bean,每當ApplicationContext發(fā)布ApplicationEvent時,ApplicationListener Bean將自動被觸發(fā)。這種事件機制都必須需要程序顯示的觸發(fā)。
spring boot中支持的事件類型如下:
- ApplicationFailedEvent:該事件為spring boot啟動失敗時的操作
- ApplicationPreparedEvent:上下文context準備時觸發(fā)
- ApplicationReadyEvent:上下文已經(jīng)準備完畢的時候觸發(fā)
- ApplicationStartedEvent:spring boot 啟動監(jiān)聽類
- SpringApplicationEvent:獲取SpringApplication
- ApplicationEnvironmentPreparedEvent:環(huán)境事先準備
SpringBoot監(jiān)聽ApplicationReadyEvent事件用例
自定義監(jiān)聽器
解決mybatis多數(shù)據(jù)源,可以在項目啟動的時候候指定數(shù)據(jù)源
package com.sl.listener;import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component;import javax.annotation.Resource; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Stream;/*** @author shuliangzhao* @Title: MyApplicationEventListener* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/10/17 20:24*/ @Component public class MyApplicationEventListener implements ApplicationListener<ApplicationReadyEvent> {@Resource(name = "targetSqlSessionTemplate")private SqlSessionTemplate targetSqlSessionTemplate;@Resource(name = "midSqlSessionTemplate")private SqlSessionTemplate midSqlSessionTemplate;//包名 不同的包名以逗號分隔@Value("{taget.source}")private String targetSource;//包名@Value("{mid.source}")private String midSource;@Overridepublic void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {ConfigurableApplicationContext applicationContext = applicationReadyEvent.getApplicationContext();Map<String, SqlSessionDaoSupport> beanMap = applicationContext.getBeansOfType(SqlSessionDaoSupport.class);String[] targetScanPath = targetSource.split(",");String[] midScanPath = midSource.split(",");List<String> targetList = Arrays.asList(targetScanPath);List<String> midList = Arrays.asList(midScanPath);beanMap.forEach((k,v) -> {String name = v.getClass().getPackage().getName();if (targetList.contains(name)) {v.setSqlSessionTemplate(targetSqlSessionTemplate);}else if (midList.contains(name)) {v.setSqlSessionTemplate(midSqlSessionTemplate);} } );} }總結
以上是生活随笔為你收集整理的SpringBoot ApplicationListener监听器的使用-监听ApplicationReadyEvent事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring AOP注解方式实现日志管理
- 下一篇: gradle idea java ssm