@ConfigurationProperties
@ConfigurationProperties
不一定要配合@EnableConfigurationProperties()
使用
用来代替@Value("${property}")
的方式来自动话地为bean绑定Environment
中的属性,不过需要注意的一点是@Value
内是支持SpEL的,但@ConfigurationProperties
不支持
Feature | @ConfigurationProperties |
@Value |
---|---|---|
Relaxed binding | Yes | No |
Meta-data support | Yes | No |
SpEL evaluation |
No | Yes |
但在使用前要注意,只用@ConfigurationProperties
注解的bean并没有被注册到上下文中,必须使用如下方法,将其注册到上下文中成为真正的bean
示例yaml:
foo:
remote-address: 192.168.1.1
security:
username: foo
roles:
- USER
- ADMIN
- 添加到
@Configuration
类的被@Bean
注解的方法上
@Configuration
public class MyConfig {
//...
@ConfigurationProperties("foo")
@Bean
public MyProperties myProperties() {
return new MyProperties();
}
}
- 添加到普通的bean定义上,配合
@Component
@Component
@ConfigurationProperties("foo")
public class MyProperties {
}
- 通过
@EnableConfigurationProperties()
注册
//只添加这个
@ConfigurationProperties("foo")
public class MyProperties {
}
找一个@Configuration
类
@Configuration
//注册只被@ConfigurationProperties注解的属性类
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration {
}