只需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注解 , 该注解用于标注需要打印执行时间的方法 。
第三步META-INF/spring.factoriesMETA-INF/spring.factories是spring的工厂机制 , 在这个文件中定义的类 , 都会被自动加载 。 多个配置使用逗号分割 , 换行用
如果有兴趣可以查看这2篇blog:
2.@Enable驱动原理(设置连接)
3.@EnableAutoConfiguration处理逻辑(设置连接)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.shanyuan.autoconfiguration.aspectlog.AspectLogAutoConfiguration第四步打包测试这是我们最终的目录结构
推荐阅读
- 再忆两岸战疫共情故事 台湾青年:相信自己是那打败黑暗的一道光
- 星车记|9万买了一辆宝马5系,本以为自己捡到宝,拆开底盘一看维修工懵了
- 墨西哥的毒枭拥有各种产业链,还有自己的军队,这武器装备不差
- 啊慧说情感|“你自己都快养不活自己了,还充什么大款?”
- 慢慢变好,是给自己最好的礼物
- L娱音袅袅|芈月传:芈月坦诚地对秦王说出自己的梦想,秦王听罢却杀心顿起
- 这段话很现实,送给自己
- 苦要自己尝|宝宝为什么更爱吃妈妈做的饭?“妈妈的味道”竟藏着大的秘密
- 作死|史上最作死的太监: 明明是件美差, 愣是让他把自己作上了黄泉路
- 科普知识大揭秘:为什么喷火器能烧毁对方而不会引燃自己?
