Springboot插件開發(fā)實(shí)戰(zhàn)分享
一 背景
項(xiàng)目新增監(jiān)控系統(tǒng),對各個(gè)系統(tǒng)進(jìn)行監(jiān)控接口調(diào)用情況,初期的時(shí)候是在各個(gè)項(xiàng)目公共引用的依賴包里面新增aop切面來完成對各個(gè)系統(tǒng)的接口調(diào)用進(jìn)行監(jiān)控,但是這樣有缺點(diǎn),一是不同項(xiàng)目的接口路徑不同,導(dǎo)致aop切面要寫多個(gè)切面路徑,二是一些不需要進(jìn)行監(jiān)控的系統(tǒng),因?yàn)橐肓斯舶脖槐O(jiān)控了,這樣侵入性就太強(qiáng)了。為了解決這個(gè)問題,就可以通過springboot的可插拔屬性了。
二 監(jiān)控日志插件開發(fā)
1 新建aop切面執(zhí)行類MonitorLogInterceptor
@Slf4j public class MonitorLogInterceptor extends MidExpandSpringMethodInterceptor<MonitorAspectAdviceProperties> { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object result = null; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); //拿到請求的url String requestURI = request.getRequestURI(); if (StringUtils.isEmpty(requestURI)) { return result; } try { result = methodInvocation.proceed(); } catch (Exception e) { buildRecordData(methodInvocation, result, requestURI, e); throw e; } //參數(shù)數(shù)組 buildRecordData(methodInvocation, result, requestURI, null); return result;
我們可以看到它實(shí)現(xiàn)了MidExpandSpringMethodInterceptor<T>
@Slf4j public abstract class MidExpandSpringMethodInterceptor<T> implements MethodInterceptor { @Setter @Getter protected T properties; /** * 主動(dòng)注冊,生成AOP工廠類定義對象 */ protected String getExpression() { return null; } @SuppressWarnings({"unchecked"}) public AbstractBeanDefinition doInitiativeRegister(Properties properties) { String expression = StringUtils.isNotBlank(this.getExpression()) ? this.getExpression() : properties.getProperty("expression"); if (StringUtils.isBlank(expression)) { log.warn("中臺(tái)SpringAop插件 " + this.getClass().getSimpleName() + " 缺少對應(yīng)的配置文件 或者 是配置的攔截路徑為空 導(dǎo)致初始化跳過"); return null; } BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(AspectJExpressionPointcutAdvisor.class); this.setProperties((T) JsonUtil.toBean(JsonUtil.toJson(properties), getProxyClassT())); definition.addPropertyValue("advice", this); definition.addPropertyValue("expression", expression); return definition.getBeanDefinition(); } /** * 獲取代理類上的泛型T * 單泛型 不支持多泛型嵌套 */ private Class<?> getProxyClassT() { Type genericSuperclass = this.getClass().getGenericSuperclass(); ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; return (Class<?>) parameterizedType.getActualTypeArguments()[0]; } }
而最終是實(shí)現(xiàn)了MethodInterceptor,這個(gè)接口是 方法攔截器,用于Spring AOP編程中的動(dòng)態(tài)代理.實(shí)現(xiàn)該接口可以對需要增強(qiáng)的方法進(jìn)行增強(qiáng).
我們注意到我的切面執(zhí)行類并沒有增加任何@Compont和@Service等將類注入到spring的bean中的方法,那他是怎么被注入到bean中的呢,因?yàn)槭褂昧藄pi機(jī)制
SPI機(jī)制的實(shí)現(xiàn)在項(xiàng)目的資源文件目錄中,增加spring.factories文件,內(nèi)容為
com.dst.mid.common.expand.springaop.MidExpandSpringMethodInterceptor=\
com.dst.mid.monitor.intercept.MonitorLogInterceptor
這樣就可以在啟動(dòng)過程直接被注冊,并且被放到spring容器中了。還有一個(gè)問題就是,切面執(zhí)行類有了,切面在哪里呢。
@Configuration @Slf4j @Import(MidExpandSpringAopAutoStarter.class) public class MidExpandSpringAopAutoStarter implements ImportBeanDefinitionRegistrar { private static final String BEAN_NAME_FORMAT = "%s%sAdvisor"; private static final String OS = "os.name"; private static final String WINDOWS = "WINDOWS"; @SneakyThrows @SuppressWarnings({"rawtypes"}) @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { // 1 獲取MidExpandSpringMethodInterceptor類的所有實(shí)現(xiàn)集合 List<MidExpandSpringMethodInterceptor> list = SpringFactoriesLoader.loadFactories(MidExpandSpringMethodInterceptor.class, null); if (!CollectionUtils.isEmpty(list)) { String expandPath; Properties properties; BeanDefinition beanDefinition; // 2 遍歷類的所有實(shí)現(xiàn)集合 for (MidExpandSpringMethodInterceptor item : list) { // 3 獲取資源文件名稱 資源文件中存儲(chǔ)需要加入配置的 expandPath = getExpandPath(item.getClass()); // 4 加載資源文件 properties = PropertiesLoaderUtils.loadAllProperties(expandPath + ".properties"); // 5 賦值beanDefinition為AspectJExpressionPointcutAdvisor if (Objects.nonNull(beanDefinition = item.doInitiativeRegister(properties))) { // 6 向容器中注冊類 注意這個(gè)beanname是不存在的,但是他賦值beanDefinition為AspectJExpressionPointcutAdvisor是動(dòng)態(tài)代理動(dòng)態(tài)生成代理類所以不會(huì)報(bào)錯(cuò) registry.registerBeanDefinition(String.format(BEAN_NAME_FORMAT, expandPath, item.getClass().getSimpleName()), beanDefinition); } } } } /** * 獲取資源文件名稱 */ private static String getExpandPath(Class<?> clazz) { String[] split = clazz.getProtectionDomain().getCodeSource().getLocation().getPath().split("/"); if (System.getProperty(OS).toUpperCase().contains(WINDOWS)) { return split[split.length - 3]; } else { return String.join("-", Arrays.asList(split[split.length - 1].split("-")).subList(0, 4)); } } }
這個(gè)就是切面注冊類的處理,首先實(shí)現(xiàn)了ImportBeanDefinitionRegistrar
,實(shí)現(xiàn)他的registerBeanDefinitions
方法可以將想要注冊的類放入spring容器中,看下他的實(shí)現(xiàn)
- 1 獲取MidExpandSpringMethodInterceptor類的所有實(shí)現(xiàn)集合
- 2 遍歷類的所有實(shí)現(xiàn)集合
- 3 獲取資源文件名稱 資源文件中存儲(chǔ)需要加入配置的
- 4 加載資源文件
- 5 賦值beanDefinition為AspectJExpressionPointcutAdvisor
- 6 向容器中注冊類 注意這個(gè)beanname是不存在的,但是他賦值beanDefinition為AspectJExpressionPointcutAdvisor是動(dòng)態(tài)代理動(dòng)態(tài)生成代理類所以不會(huì)報(bào)錯(cuò)
看到這里,還有一個(gè)問題ImportBeanDefinitionRegistrar
實(shí)際上是將類注冊到容器中,但是還需要一個(gè)步驟就是他要被容器掃描才行,以往的方式是項(xiàng)目中通過路徑掃描,但是我們是插件,不能依賴于項(xiàng)目,而是通過自己的方式處理,這時(shí)候就需要用@Import(MidExpandSpringAopAutoStarter.class)
來處理了。
通過以上處理就實(shí)現(xiàn)了監(jiān)控插件的處理,然后再使用時(shí),只需要將這個(gè)項(xiàng)目引入到不同需要監(jiān)控的項(xiàng)目上就可以了。
三 總結(jié)
開發(fā)一個(gè)插件可以降低代碼的侵入性,過程中我們不能用以前@Component等注解來掃描而是要通過一些spring暴露的其他來處理,所以開發(fā)一個(gè)插件對個(gè)人的提升還是蠻大的,希望對大家有所幫助。
到此這篇關(guān)于Springboot插件開發(fā)實(shí)戰(zhàn)分享的文章就介紹到這了,更多相關(guān)Springboot插件 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java使用Rxtx實(shí)現(xiàn)串口通信調(diào)試工具
這篇文章主要為大家詳細(xì)介紹了java使用Rxtx實(shí)現(xiàn)簡單串口通信調(diào)試工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12SpringBoot整合Kotlin構(gòu)建Web服務(wù)的方法示例
這篇文章主要介紹了SpringBoot整合Kotlin構(gòu)建Web服務(wù)的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02怎么把本地jar包放入本地maven倉庫和遠(yuǎn)程私服倉庫
這篇文章主要介紹了怎么把本地jar包放入本地maven倉庫和遠(yuǎn)程私服倉庫的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06Java為何需要平衡方法調(diào)用與內(nèi)聯(lián)
這篇文章主要介紹了Java為何需要平衡方法調(diào)用與內(nèi)聯(lián),幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2021-01-01springboot動(dòng)態(tài)加載jar包動(dòng)態(tài)配置實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于springboot動(dòng)態(tài)加載jar包動(dòng)態(tài)配置的相關(guān)資料,在項(xiàng)目開發(fā)的過程中,有時(shí)候需要?jiǎng)討B(tài)靈活的加載某個(gè)jar包并執(zhí)行其里面的方法的時(shí)候,需要的朋友可以參考下2023-11-11詳解Spring Security的Web應(yīng)用和指紋登錄實(shí)踐
這篇文章主要介紹了詳解Spring Security的Web應(yīng)用和指紋登錄實(shí)踐,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03JavaWeb實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)(2)
這篇文章主要介紹了JavaWeb實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)的第二篇,實(shí)現(xiàn)學(xué)生管理系統(tǒng)的查找和添加功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08