只需4步,自己搞个 Spring Boot Starter


只需4步,自己搞个 Spring Boot Starter

文章插图

作者 | 温安适
来源 | https://my.oschina.net/floor/blog/4435699
引言【只需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官方文档摘录如下:

Do not start your module names with spring-boot, even if you use a different Maven groupId. We may offer official support for the thing you auto-configure in the future.
As a rule of thumb, you should name a combined module after the starter.
从这段话可以看出spring-boot-starter命名的潜规则 。
命名潜规则
spring-boot-starter-XX是springboot官方的starter
XX-spring-boot-starter是第三方扩展的starter
打印方法执行时间的功能,需要用到aop,咱们的项目就叫做
aspectlog-spring-boot-starter吧 。
项目的pom文件如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.Apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>org.example</groupId>    <artifactId>aspectlog-spring-boot-starter</artifactId>    <version>1.0.2</version>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.1.15.RELEASE</version>    </parent>        <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-autoconfigure</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-aop</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-configuration-processor</artifactId>            <optional>true</optional>        </dependency>    </dependencies></project>关于spring-boot-configuration-processor的说明,引自springBoot官方文档:

Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file ( META-INF/spring-autoconfigure-metadata.properties ). If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time. It is recommended to add the following dependency in a module that contains auto-configurations:
org.springframework.boot
spring-boot-autoconfigure-processor
true
简单说就是:写starter时,在pom中配置spring-boot-autoconfigure-processor,在编译时会自动收集配置类的条件,写到一个META-INF/spring-autoconfigure-metadata.properties中 。
第二步写自动配置逻辑各种condition
类型注解说明Class Conditions类条件注解@ConditionalOnClass当前classpath下有指定类才加载@ConditionalOnMissingClass当前classpath下无指定类才加载
Bean ConditionsBean条件注解@ConditionalOnBean当期容器内有指定bean才加载@ConditionalOnMissingBean当期容器内无指定bean才加载


推荐阅读