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();
}
}