Spring@Value设置默认值本⽂转载⾃
1.
在 Spring 组件中使⽤ @Value 注解的⽅式,很⽅便的读取 properties ⽂件的配置值。
2.
声明的变量中使⽤。
public static class FieldValueTestBean {
@Value("#{ systemProperties['ion'] }")
private String defaultLocale;
}
setter ⽅法中。
public static class PropertyValueTestBean {
private String defaultLocale;
@Value("#{ systemProperties['ion'] }")
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['ion'] }") String defaultLocale) {
this.defaultLocale = defaultLocale;
}
// ...
}
构造⽅法。
public class MovieRecommender {
private String defaultLocale;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
@Value("#{systemProperties['untry']}") String defaultLocale) {
spring怎么读取propertiesthis.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}")
private Integer intWithDefaultValue;
5.
数组的默认值可以使⽤逗号分割。
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;
使⽤ Spring Expression Language (SpEL) 设置默认值。
下⾯的代码标⽰在systemProperties属性⽂件中,如果没有设置 some.key 的值,my default system property value 会被设置成默认值。@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;
7.
上⾯讲解使⽤ Spring @Value 为属性设置默认值。在项⽬中,提供合理的默认值,在⼤多情况下不⽤任何配置,就能直接使⽤。达到零配置的效果,降低被⼈使⽤的门槛。简化新Spring应⽤的搭建、开发、部署过程。
8.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。