Spring boot 自定义 starter
1、starter 启动原理
- 定义一个场景启动器starter,让外部引入,例如:spring-boot-starter-test
- 启动器中并没有源码,而是声明当前场景中有哪些依赖,将相应的依赖导入。而真正的自动配置功能在spring-boot-test-autoconfigure
-
在autoconfigure包中配置使用META-INF/spring.factories中EnableAutoConfiguration的值,使得项目启动时加载指定的自动配置类
-
注意:在spring boot2.7改变了自动配置的路径,需要自动装配的类被声明在META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中
大致流程:引入starter > 引入xxAutoConfiguration > 将相应的组件放入容器中 > 绑定xxProperties > 获取配置项
-
2、自定义starter
hello-spring-boot-starter(启动器,用于被外部引入)
引入自动配置包
<dependency>
<groupId>com.example</groupId>
<artifactId>hello-spring-boot-starter-autoconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
hello-spring-boot-starter-autoconfiguration(自动配置包,用于功能实现)
功能:定义一个HelloService组件,根据传入的名称以及配置的前缀和后缀返回一个字符串。
/**
* 用于自动配置的功能组件。
* 默认不放在容器中,由自动配置类决定是否加载
* @Author: junwe
* @Date: 2022/6/29 16:41
*/
public class HelloService {
@Autowired
private HelloProperties helloProperties;
public String sayHello(String name) {
return helloProperties.getPrefix() + ": "+ name + helloProperties.getSuffix();
}
}
前缀、后缀和配置属性test.hello绑定
/**
* 绑定配置文件属性
* @Author: junwe
* @Date: 2022/6/29 16:44
*/
@ConfigurationProperties("test.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
定义自动配置类决定是否将HelloService组件放入容器中
@Configuration
// HelloService中需要注入HelloProperties,将HelloProperties放入容器中
// HelloProperties和test.hello配置绑定
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
@Bean
// 当容器中不存在HelloService该配置生效
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService() {
return new HelloService();
}
}
最重要的一步,将自动配置类HelloServiceAutoConfiguration写入META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中,自动配置类才可能生效。
将自动配置包和启动器分别打包到本地仓库,此时就可以被其他项目依赖了。
测试一把。新建一个hello-test项目,在pom文件中添加依赖
<dependency>
<groupId>org.example</groupId>
<artifactId>hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
注入HelloService组件,调用相关功能。
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello() {
String s = helloService.sayHello("zhangsan");
return s;
}
}
添加相关配置
test.hello.prefix=hello
test.hello.suffix=666
此时HelloService的sayHello方法可以根据配置内容返回
3、总结
首先引入自定义starter
自定义starter中引入了自动配置场景
自动配置场景引入了自动配置类HelloServiceAutoConfiguration
自动配置类在容器中没有相关组件的时候会创建好相关组件
组件的相关属性可以通过配置来更改