ConfigurationProperties 和EnableConfigurationProperties的区别
当@EnableConfigurationProperties注解应用到你的@Configuration时, 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。 这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。
@ConfigurationProperties(prefix = "service.properties")
public class HelloServiceProperties {
private static final String SERVICE_NAME = "test-service";
private String msg = SERVICE_NAME;
set/get
}
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
}
@RestController
public class ConfigurationPropertiesController {
@Autowired
private HelloServiceProperties helloServiceProperties;
@RequestMapping("/getObjectProperties")
public Object getObjectProperties () {
System.out.println(helloServiceProperties.getMsg());
return myConfigTest.getProperties();
}
}
当@EnableConfigurationProperties的注解删掉时HelloServiceProperties 这个类找不到 所以这两个注解配合着使用
2.好处:
@EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入到spring