本文轉載自Spring @Value 設置默認值
概述
在 Spring 組件中使用 @Value 注解的方式,很方便的讀取 properties 文件的配置值。
使用場景
聲明的變量中使用。
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;
}
// ...
}
字符串
字符串類型的屬性設置默認值。
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
some.key 沒有設置值,stringWithDefaultValue 變量值將會被設置成 my default value 。
如果默認值設為空,也將會被設置成默認值。
@Value("${some.key:}")
private String stringWithBlankDefaultValue;
基本類型
基本類型設置默認值。
@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}")
private Integer intWithDefaultValue;
數組
數組的默認值可以使用逗號分割。
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;
SpEL
使用 Spring Expression Language (SpEL) 設置默認值。
下面的代碼標示在systemProperties屬性文件中,如果沒有設置 some.key 的值,my default system property value 會被設置成默認值。
@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;
結語
上面講解使用 Spring @Value 為屬性設置默認值。在項目中,提供合理的默認值,在大多情況下不用任何配置,就能直接使用。達到零配置的效果,降低被人使用的門檻。簡化新Spring應用的搭建、開發、部署過程。
