SpringBoot中自定义start:
1.分析原生的start
1.每一个xxx-start中都有一个xxx-autoconfigure
2.每一个xxx-autoconfigure都有一个spring-boot-start
3.每一个xxx-autoconfigure都有一个META-INF的文件夹里面都有一个spring.factories,
里面配置了EnableAutoConfiguration的值,使项目一启动就加载指定的自动配置类
4.编写自动配置类:xxxAutoconfigurtaion-->xxxProperties(并进行配置绑定)
,在进行组件的配置
5.流程是:引入starter--->xxxAutoconfiguration--->容器中放入组件--->绑定xxxProperties--->配置项
代码:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.4.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.4.1</version>
<scope>compile</scope>
</dependency>
2.自定义start
1.创建一个空的工程,添加一个maven项目和一个springboot的项目,目录结构如下:
2.在hellospringbootstarter这个模块下的pom文件中引入hello-spring-boot-starter-autoconfigure这个模块的坐标
3.接下来在hello-spring-boot-starter-autoconfigure这个模块中编写三个类
4.在HelloService中自动注入helloProperties这个对象并引入该对象的属性在sayHello这个方法中.
public class HelloService {
@Autowired
HelloProperties helloProperties;
public String sayHello(String userName){
return helloProperties.getPrefix()+": "+userName+"->"+helloProperties.getSuffix();
}
}
5.在 HelloProperties这个类中加入注解@ConfigurationProperties(prefix = “hello”)进行配置绑定
@ConfigurationProperties(prefix = "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;
}
}
6.最后编写HelloServiceAutoConfiguration类,将该类变为一个配置类,并将HelloService加入容器中
@Configuration
@EnableConfigurationProperties(value = {HelloProperties.class})
public class HelloServiceAutoConfiguration {
@Bean
@ConditionalOnMissingBean(value = {HelloService.class})
public HelloService helloService(){
HelloService helloService = new HelloService();
return helloService;
}
7.最后在hello-spring-boot-starter-autoconfigure这个模块的resources目录下创建一个META-INF文件夹编写一个spring.factories文件配置好使项目启动自动加载的配置类
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.boot.hello.auto.HelloServiceAutoConfiguration