命名规范
start命名规范一般是模块名xxx-spring-boot-starter
以及模块名xxx-spring-boot-autoconfigure
模块
starter一般有两个模块,一个是starter,一个是autoconfigure
autoconfigure模块
pom.xml必须加入这两个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
我自己会加入lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
先创建xxxproperties
,通过@ConfigurationProperties注解来映射配置文件的值,prefix属性指前缀
@Data
@ConfigurationProperties(prefix = "xkl.student")
public class StudentProperties {
private String name = "李四";
private Integer age = 18;
private boolean enable = false;
}
赋值是为了让属性有默认的值,如果不想有默认的值可不赋值,后续他人在配置文件中可以使用会覆盖掉默认值,
enable
属性后续有用
创建一个想让这个starter提供的服务,比如我想让这个starter返回一个学生给我
//获取学生服务
public class StudentService {
private final StudentProperties studentProperties;
public StudentService(StudentProperties studentProperties) {
this.studentProperties = studentProperties;
}
public String getStudent(){
return "学生姓名:" + studentProperties.getName() +
",年龄:" + studentProperties.getAge();
}
}
创建AutoConfiguration
@Configuration
@EnableConfigurationProperties(StudentProperties.class)
//Spring中引用了某个类才会构建这个bean
@ConditionalOnClass(StudentService.class)
//控制配置类是否生效,value指与配置文件的属性做对比,havingValue指当值是true才生效
@ConditionalOnProperty(value = "yhlz.student.enable",havingValue = "true")
public class StudentAutoConfiguration {
@Autowired
private StudentProperties studentProperties;
@Bean
//当spring容器有相同的bean则不会再创建这个bean
@ConditionalOnMissingBean
public StudentService getStudentService(){
return new StudentService(studentProperties);
}
}
最重要的一步,在resources下创建META-INF文件夹,再创建spring.factories,为什么要这样做可以去了解一下spring boot的自动化配置原理。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.yhlz.config.StudentAutoConfiguration
多个值可用,\
分割
打包安装到仓库里面
starter模块
主要作用就是把autoconfigure包一层,pom.xml
引用autoconfigure模块
<dependencies>
<dependency>
<groupId>org.yhlz</groupId>
<artifactId>student-spring-boot-autoconfigure</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
测试
测试也很简单,直接使用StudentService来调用它的get方法,返回它默认的值,假如想设定其他值就可以在配置文件中修改
可以将该值修改为false来让该配置失效