1 创建一个自定义Starter项目

CustomConfig
@Configuration
@EnableConfigurationProperties(value = CustomProperties.class) // 使配置类生效
@ConditionalOnProperty(prefix = "mmw.config", name = "enable", havingValue = "true") // 自动装配条件
public class CustomConfig {
@Resource
private CustomProperties customProperties;
@Bean
public ConfigService defaultCustomConfig() {
return new ConfigService(customProperties.getAge(), customProperties.getName(), customProperties.getInfo());
}
}
CustomProperties
@ConfigurationProperties(prefix = "mmw.config")
public class CustomProperties {
private Integer age;
private String name;
private String info;
// getter/setter
}
ConfigService
public class ConfigService {
private Integer age;
private String name;
private String info;
public ConfigService(Integer age, String name, String info) {
this.age = age;
this.name = name;
this.info = info;
}
public String showConfig() {
return "ConfigService{" +
"age=" + age +
", name='" + name + '\'' +
", info='" + info + '\'' +
'}';
}
}
META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mmw.demo.config.CustomConfig
2 创建一个测试springBoot项目

application.yml
mmw:
config:
enable: true
age: 26
name: 'my custom starter'
info: 'custom web info...'
server:
port: 8081
spring:
application:
name: customStarterTestDemo
TestController
@RestController
public class TestController {
@Resource
private ConfigService configService;
@GetMapping("/test")
public String test() {
return configService.showConfig();
}
}
3 测试自动装配

本文详细介绍了如何创建一个自定义的Spring Boot Starter项目,包括配置类`CustomConfig`、配置属性`CustomProperties`和`ConfigService`的实现。通过`@EnableConfigurationProperties`和`@ConditionalOnProperty`注解实现条件装配。接着,在测试项目中,配置了相关属性并创建了`TestController`以展示配置信息。测试结果显示自定义Starter成功工作。
2599

被折叠的 条评论
为什么被折叠?



