Overview
Spring提供了如下几种方式读取application.properties的配置:
- @Value
- @ConfigurationProperties
- @Component + @ConfigurationProperties
- @EnableConfigurationProperties + @ConfigurationProperties
@Value
@Value被Spring用来直接注入配置文件的属性值,有两种情况:
- 默认从application.properties文件中读取属性值,不需要额外设置。
- 如果是读取其他文件内容,需要过@PropertySource设置路径信息。
@ConfigurationProperties + @Component
@ConfigurationProperties被Springboot用来将配置文件的属性注入到一个bean对象
(POJO对象,对应于properties文件中的某一类属性)的成员变量中。
@Component用来声明这个POJO为bean,然后再通过@Autowired或者构造器方式将其注入到其他类中来使用。
@ConfigurationProperties + @EnableConfigurationProperties
此种方式是本文重点。它通过@ConfigurationProperties将配置映射到一个POJO对象中,但是不声明@Component.
@ConfigurationProperties(prefix = "demo")
public class DemoProperties{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
然后在需要用到的地方,用@EnableConfigurationProperties直接声明上述POJO类,来注入对应的配置。
@Configuration
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
private DemoProperties dp;
public DemoAutoConfiguration(DemoProperties dp) {
this.dp = dp;
}
...
}
注意此处用的是构造器注入,也可以用@Autowired的方式注入到指定的成员变量里。
总结
@EnableConfigurationProperties + @ConfigurationProperties的方式是sprng boot autoconfigure机制中经常用到的方式,需要特别关注!