Spring @Value 设置默认值
5 年前
题图:from @baeldung
1. 概述
在 Spring 组件中使用 @Value 注解的方式,很方便的读取 properties 文件的配置值。
2.使用场景
声明的变量中使用。
public static class FieldValueTestBean {
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;
}
setter 方法中。
public static class PropertyValueTestBean {
private String defaultLocale;
@Value("#{ systemProperties['user.region'] }")
public void setDefaultLocale(String defaultLocale) {
this.defaultLocale = defaultLocale;
}
方法。
public class SimpleMovieLister {
private MovieFinder movieFinder;
private String defaultLocale;
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
// ...
}
构造方法。
public class MovieRecommender {
private String defaultLocale;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
@Value("#{systemProperties['user.country']}") String defaultLocale) {
this.customerPreferenceDao = customerPreferenceDao;
this.defaultLocale = defaultLocale;
// ...
}
3. 字符串
字符串类型的属性设置默认值。
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
some.key 没有设置值,stringWithDefaultValue 变量值将会被设置成 my default value 。
如果默认值设为空,也将会被设置成默认值。
@Value("${some.key:}")
private String stringWithBlankDefaultValue;
4. 基本类型
基本类型设置默认值。
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private int intWithDefaultValue;
包装类型设置默认值。
@Value("${some.key:true}")
private Boolean booleanWithDefaultValue;
@Value("${some.key:42}")