根据SpringBoot自动配置原理,我们自己也能写出自定义自动配置原理SpringBoot的starter启动器
最终目录
接下来写一个HelloWorld的简单启动器
引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
</dependencies>
自定义启动器名称与版本
pom.xml中可修改
<groupId>com.tpa</groupId>
<artifactId>spring-boot-starter-tpa</artifactId>
<version>1.0-SNAPSHOT</version>
属性配置类
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private static final String MSG = "world";
private String msg = MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
判断依据类
根据此类的存在与否来创建这个类的bean
public class HelloService {
private String msg;
public String sayHello(){
return "Hello "+msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
自动配置类
根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass判断HelloService这个类在类路径中是否存在,且当容器中没有这个Bean的情况下自动配置这个bean
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
}
}
注册配置
在src/main/resources
下新建META-INF/spring.factories
如果有多个自动配置,则用“,”隔开
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.tpa.service.HelloServiceAutoConfiguration
最后用maven打成jar包即可,自动存入maven仓库中
测试
在其他项目中引入我们的启动器依赖
<dependency>
<groupId>com.tpa</groupId>
<artifactId>spring-boot-starter-tpa</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
在这个类中没有创建HelloService类,但却可以直接调用HelloService及其API,说明我们的自定义启动器创建成功了
测试代码
测试结果