在我们使用SpringBoot starter的时候,比如MyBatis,我们只需要引入MyBatis相关的starter即可,然后配置文件中写好配置就行,以前我们需要配置MyBatis的配置文件,还有各种各样的配置,这样就简单多了
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
1:既然starter这么好用,那么我们自己也动手搭建一个吧,首先创建一个SpringBoot项目,pom.xml文件引入一个依赖
SpringBoot版本我是用的2.2.2版本的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
2:编写属性源
@ConfigurationProperties(prefix = "coco")
public class StarterSource {
private String type;
private String rate;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
3:编写服务类,给外界提供接口服务的
public class StartService {
private StarterSource starterSource;
public StartService(StarterSource starterSource) {
this.starterSource = starterSource;
}
public String getType() {
return starterSource.getType();
}
public String getRate() {
return starterSource.getRate();
}
}
4:编写属性自动配置类
@Configuration
@EnableConfigurationProperties(StarterSource.class)
@ConditionalOnProperty(name = "weather.enable",havingValue = "enable")
public class StarterAutoConfiguration {
@Autowired
private StarterSource starterSource;
@Bean
@ConditionalOnMissingBean(StartService.class)
public StartService startService() {
return new StartService(starterSource);
}
}
5:在spring.factories文件添加自动配置类的实现,在resource目录下创建一个META-INF的文件夹,文件夹里面创建一个spring.factories的文件,文件内容如下
//配置我们自己的属性自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.starter.StarterAutoConfiguration
6:安装一个maven help的插件,插件安装好之后,右键项目 Run Maven-> clean install,编译成功之后到另外一个SpringBoot项目中引入这个依赖
7:准备测试:
coco.type=java
coco.rate=spark
weather.enable=enable
新建一个Controller
@Autowired
private StartService startService;
@GetMapping("/test")
public String test() {
return startService.getType();
}
8:浏览器输入localhost:8080/test 就可以看到输出java了,因为我们配置type的值就是java