一、新建maven 项目 引入pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!--springboot自动配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- 在配置文件中配置属性时 可以提示属性信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
二、新建配置类
/**
* 属性配置类 配置文件的前缀first
*/
@ConfigurationProperties(prefix = "first")
public class FirstProperties {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
三、建starter业务类
public class FirstService {
private String msg;
public String sayMsg(){
return "-----" + msg + " ----";
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
四、建自动配置类
@Configuration //标识FirstAutoConfiguration 是一个配置类
@EnableConfigurationProperties(FirstProperties.class) //FirstAutoConfiguration 使用FirstProperties当做属性配置类
@ConditionalOnClass(FirstService.class) //当存在FirstService依赖的时候FirstAutoConfiguration才会加载到spring容器
@ConditionalOnProperty(prefix = "first",value = "enable",havingValue = "true") //当配置文件中有first.enable=true 时FirstAutoConfiguration才会加载到spring容器
public class FirstAutoConfiguration {
@Autowired
private FirstProperties firstProperties;
public FirstService getFirstService(){
FirstService firstService = new FirstService();
firstService.setMsg(firstProperties.getMsg());
return firstService;
}
}
五、再resources 目录下新建一个META-INF目录 再META-INF目录下 新建一个spring.factories文件 内容如下
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xiao.config.FirstAutoConfiguration
六、再新建一个maven项目 引入自定义starter 测试
1、新建maven项目 pom.xml中引用 自定义starter
<dependency>
<groupId>com.xiao.bootstarter</groupId>
<artifactId>spring-boot-starter-first</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2、在application.yml配置文件中加入 属性配置
first:
msg: 11111
enable: true
3、测试starter controller
@Controller
public class TestStarterController {
@Autowired
private FirstService firstService;
@RequestMapping("testStarter")
@ResponseBody
public String testStarter(){
return firstService.sayMsg();
}
}