学 无 止 境 , 与 君 共 勉 。
自动配置
在SpringBoot中我们引用的很多包都是spring-boot-starter-XXX的格式。我们只需在Maven中引入starter依赖,SpringBoot就会自动注入需要的Bean,并进行默认配置,这是SpringBoot中的一种重要机制:自动配置。相比以前开发需要配置大量的XML文件,SpringBoot大大减少了开发人员的工作量。这些依赖都遵循着约定俗成的默认配置,同时允许我们调整这些配置,这就是我们通常讲的约定大于配置。
应用场景
有时候在项目中我们需要集成第三方工具,比如极光推送,并且在多个项目中都需要用到。这就需要在每个项目中复制一份代码,重新集成,这造成了大量的重复工作,而且出了BUG修复时,每个项目都需要去修复一遍,增加工作量。这时我们就可以将这种业务封装成一个starter,需要用的时候直接在pom中引用依赖既可,比如:
- 极光推送
- 短信业务
- 文件上传
- 接口访问监控
自定义starter
一个完整的SpringBootStarter通常包含autoconfigure和starter两个模块,当然也可以将他们全都合并到starter模块中。
命名
官方命名:
- spring-boot-starter-XXX
- spring-boot-starter-jdbc
- spring-boot-starter-data-redis
非官方命名:
- XXX-spring-boot-starter
- mybatis-spring-boot-starter
- druid-spring-boot-starter
创建autoconfigure模块
该模块主要是我们的具体业务的实现,通常包含了:
- 参数配置类(XXXProperties)
- 具体业务实现类(需要被注入到容器的Bean)
- 自动配置类(XXXAutoConfiguration)
创建一个Maven项目
这里我们类别选择maven-archetype-quickstar。t引入依赖:
<!-- Spring Boot自身的自动配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
创建参数类
参数类中设置了我们自定义starter中需要用到的配置,我们可以将其设置一个默认的值。比如redis的starter中的端口配置、连接池配置等。通过ConfigurationProperties注解,我们将properties或者yml文件中符合前缀的参数绑定到这个类的属性上
@ConfigurationProperties(prefix = "animal")
public class AnimalProperties {
private String type = "animal";
private String name;
private final Fish fish = new Fish();
private final bird bird = new bird();
public static class Fish {
private String doing;
public String getDoing() {
return doing;
}
public void setDoing(String doing) {
this.doing = doing;
}
}
public static class bird {
private String doing;
public String getDoing() {
return doing;
}
public void setDoing(String doing) {
this.doing = doing;
}
}
// 省略get set 方法
}
这里属性的值我们可以在application.properties或者yml中来直接设置:
- animal.name=XXX
- animal.type=XXX
- animal.bird.doing=XXX
- animal.fish.doing=XXX
创建业务实现类
public class AnimalService {
private AnimalProperties animalProperties;
public AnimalService(AnimalProperties animalProperties) {
this.animalProperties = animalProperties;
}
public void doing(