Sringboot 自定义启动器
开门见山:
1、创建项目:
2、配置pom文件
autoconfigure模块:(引入starter和processor依赖)
<?xml version="1.0" encoding="UTF-8"?>4.0.0 cn.sam.antass antass-spring-boot-starter-autoconfigure 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.3.2.RELEASE org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-configuration-processor
starter模块:(引入“antass-spring-boot-starter-autoconfigure”依赖)
<?xml version="1.0" encoding="UTF-8"?>4.0.0 cn.sam.antass antass-spring-boot-starter 1.0-SNAPSHOT cn.sam.antass antass-spring-boot-starter-autoconfigure 1.0-SNAPSHOT
3、项目文件:
AntassProperties:
@ConfigurationProperties(prefix = "antass.config")
public class AntassProperties {
private Boolean enable;
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
}
AntassService:
public class AntassService {
AntassProperties properties;
public Boolean config() {
return properties.getEnable();
}
public AntassProperties getProperties() {
return properties;
}
public void setProperties(AntassProperties properties) {
this.properties = properties;
}
}
AntassAutoConfiguration:
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(AntassProperties.class)
public class AntassAutoConfiguration {
@Autowired
private AntassProperties properties;
@Bean
public AntassService antassService() {
AntassService service = new AntassService();
service.setProperties(properties);
return service;
}
}
3、新建META文件(resources\META-INF\spring.factories),配置自动加载类
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ cn.sam.antass.AntassAutoConfiguration
4、将antass-spring-boot-starter-autoconfigure和antass-spring-boot-starter模块按顺序安装进maven仓库
5、再其它项目中引入:
cn.sam.antass antass-spring-boot-starter 1.0-SNAPSHOT
6、配置:(application.yml)
antass:
config:
enable: false
7、使用:
@Autowired private AntassService antassService;
8、测试:
@GetMapping("/antass")
public String testAntass() {
return String.valueOf(antassService.config());
}