-
Notifications
You must be signed in to change notification settings - Fork 141
@Value vs. @ConfigurationProperties
gexiangdong edited this page Nov 18, 2018
·
8 revisions
@Value和@ConfigurationProperties两个注解都可以从配置文件获取值并设置到属性中,用法上有区别。 @Value适用一些比较简单的情形,用得比较普遍;而@ConfigurationProperties则可适用一些@Value无法处理更复杂的情形。
@Value
@
直接写在需要从配置文件读取值的成员变量上即可。 例如:
@Service
public class XxxxService{
@Value("xxx.yyy")
private String xxxYyy;
}只有一个字符型参数value,用于标记配置文件中的key
| 参数名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| value | String | 从配置文件中哪一项读取值,支持Spring EL |
@ConfigurationProperties注解需要写到类上,为该类所有有setter方法的属性从配置文件中读取并付值。
| 参数名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| ignoreInvalidFields | boolean | false | java中被绑定的属性类型与配置文件中设置的值类型不同时是否忽略 |
| ignoreUnknownFields | boolean | true | Flag to indicate that when binding to this object invalid fields should be ignored |
| prefix | String | The name prefix of the properties that are valid to bind to this object. | |
| value | String | 同prefix,简写,支持Spring EL |
1、需要增加依赖
2、需要先开始使用配置属性的功能(不开启不出错,但不会读取配置并设置到类上)
@EnableConfigurationProperties如果信息配置在了自定义的配置文件中(不是applicaiton.yml),则可以使用@PropertySource注解来告诉spring从哪个文件读取配置信息,例如:
@PropertySource("classpath:configprops.properties")