只需4步,自己也能轻松搞个 Spring Boot Starter

引言只要你用Springboot , 一定会用到各种spring-boot-starter 。 其实写一个spring-boot-starter
, 仅需4步 。 下面我们就写一个starter , 它将实现 , 在日志中打印方法执行时间 。
第一步创建maven项目在使用spring-boot-starter , 会发现 , 有的项目名称是XX-spring-boot-starter , 有的是
spring-boot-starter-XX , 这个项目的名称有什么讲究呢?
从springboot官方文档摘录如下:

Donotstartyourmodulenameswithspring-boot,evenifyouuseadifferentMavengroupId.Wemayofferofficialsupportforthethingyouauto-configureinthefuture.
Asaruleofthumb,youshouldnameacombinedmoduleafterthestarter.
从这段话可以看出spring-boot-starter命名的潜规则 。
命名潜规则
spring-boot-starter-XX是springboot官方的starter
XX-spring-boot-starter是第三方扩展的starter
打印方法执行时间的功能 , 需要用到aop , 咱们的项目就叫做
aspectlog-spring-boot-starter吧 。
项目的pom文件如下:
4.0.0org.exampleaspectlog-spring-boot-starter1.0.2org.springframework.bootspring-boot-starter-parent2.1.15.RELEASEorg.springframework.bootspring-boot-autoconfigureorg.springframework.bootspring-boot-starter-aoporg.springframework.bootspring-boot-configuration-processortrue关于spring-boot-configuration-processor的说明 , 引自springBoot官方文档:

SpringBootusesanannotationprocessortocollecttheconditionsonauto-configurationsinametadatafile(META-INF/spring-autoconfigure-metadata.properties).Ifthatfileispresent,itisusedtoeagerlyfilterauto-configurationsthatdonotmatch,whichwillimprovestartuptime.Itisrecommendedtoaddthefollowingdependencyinamodulethatcontainsauto-configurations:
org.springframework.boot
spring-boot-autoconfigure-processor
true
简单说就是:写starter时 , 在pom中配置spring-boot-autoconfigure-processor , 在编译时会自动收集配置类的条件 , 写到一个META-INF/spring-autoconfigure-metadata.properties中 。
第二步写自动配置逻辑各种condition
下面开始写自动配置类
2.1.定义AspectLog注解 , 该注解用于标注需要打印执行时间的方法 。 @ConditionalOnProperty(prefix="aspectLog",name="enable",havingValue="https://pcff.toutiao.jxnews.com.cn/p/20200808/true",matchIfMissing=true)当配置文件有aspectLog.enable=true时开启 , 如果配置文件没有设置aspectLog.enable也开启 。
第三步META-INF/spring.factoriesMETA-INF/spring.factories是spring的工厂机制 , 在这个文件中定义的类 , 都会被自动加载 。 多个配置使用逗号分割 , 换行用
如果有兴趣可以查看这2篇blog:
2.@Enable驱动原理(设置连接)
3.@EnableAutoConfiguration处理逻辑(设置连接)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.shanyuan.autoconfiguration.aspectlog.AspectLogAutoConfiguration第四步打包测试这是我们最终的目录结构


    推荐阅读