1. starter启动原理
- starter-pom引入 autoconfigurer 包
- autoconfigure包中配置使用 META-INF/spring.factories 中 EnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
- 编写自动配置类 xxxAutoConfiguration -> xxxxProperties
- @Configuration
- @Conditional
- @EnableConfigurationProperties
- @Bean
- ……
引入starter —- xxxAutoConfiguration —- 容器中放入组件 —— 绑定xxxProperties —— 配置项
2. 自定义步骤
atguigu-hello-spring-boot-starter(启动器)
atguigu-hello-spring-boot-starter-autoconfigure(自动配置包)
在atguigu-hello-spring-boot-starter里面引入atguigu-hello-spring-boot-starter-autoconfigure的maven坐标
<?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>com.hao</groupId>
<artifactId>hao-hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.hao</groupId>
<artifactId>hao-hello-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
创建一个Service引用一个自动注入的bean
package com.hao.hello.service;
//默认不要放在容器中
public class HelloService {
@Autowired
HelloProperties helloProperties;
public String sayHello(String userName){
return helloProperties.getPrefix() + ": " + userName + "》 " + helloProperties.getSuffix();
}
}
创建一个bean设置配置文件绑定
package com.hao.hello.bean;
@ConfigurationProperties("hao.hello")
public class HelloProperties {
private String prefix;
private String suffix;
@Override
public String toString() {
return "HelloProperties{" +
"prefix='" + prefix + '\'' +
", suffix='" + 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;
}
}
创建配置类将创建的Service加入到容器中(如果用户自己创建了同名的Service类就不会自动将写好的Service类自动注入,而是以用户写的优先)
package com.hao.hello.auto;
@Configuration
@ConditionalOnMissingBean(HelloService.class)
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
return helloService;
}
}
**创建META-INF文件夹,并在META-INF文件夹下面创建spring.factories文件将自动配置的主程序类加入