使⽤@Value注解从配置⽂件中读取数组
@Value注解从配置⽂件读取数组
作⽤:从配置⽂件中取值
⽤法:
1.取单个值
(1)configuration.properties配置
(2)java⽂件⾃动注⼊
@Value("${ice.switch}")
private String statusNoticeSwitch;
2.取数组
(1)configuration.properties配置
lanwon.hospital.id=43534,234543,w353654
(2)java⽂件⾃动注⼊
@Value("#{'${lanwon.hospital.id}'.split(',')}")
private List<String> hospitalIdList;
使⽤@Value注解注⼊值(配置⽂件读取)
在 Spring 组件中使⽤ @Value 注解的⽅式,可以直接从 .properties,.yum 等配置⽂件获取配置信息便于实现项⽬的配置化运⾏。
1. 配置⽅式
1.1 使⽤
1、@Value("${key}")
2、@Value("#{configProperties[‘key']}") (SpEL表达式)
1.2 默认值配置
1、基础⽅式: ${key}:defaultvalue
2. 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;
2. 使⽤场景
2.1 声明的变量
public static class FieldValueTestBean {
@Value("#{ systemProperties['ion'] }")
private String defaultLocale;
}
2.2 setter ⽅法
public static class PropertyValueTestBean {
private String defaultLocale;
@Value("#{ systemProperties['ion'] }")
public void setDefaultLocale(String defaultLocale) {
this.defaultLocale = defaultLocale;
}
}
2.3 ⽅法
public class SimpleMovieLister {
private MovieFinder movieFinder;
private String defaultLocale;
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['ion'] }") String defaultLocale) {
this.defaultLocale = defaultLocale;
}
// ...
}
2.4 构造⽅法
public class MovieRecommender {
private String defaultLocale;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
@Value("#{systemProperties['untry']}") String defaultLocale) {
this.customerPreferenceDao = customerPreferenceDao;
this.defaultLocale = defaultLocale;
}
spring怎么读取properties// ...
}
3 各种属性的注⼊及其默认值设置
3.1 字符串
字符串类型的属性设置默认值。
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
some.key 没有设置值,stringWithDefaultValue 变量值将会被设置成 my default value 。如果默认值设为空,也将会被设置成默认值。
@Value("${some.key:}")
private String stringWithBlankDefaultValue;
3.2 基本类型
基本类型设置默认值。
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private int intWithDefaultValue;
3.3 包装类型
包装类型设置默认值。
@Value("${some.key:true}")
private Boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private Integer intWithDefaultValue;
3.4 数组
数组的默认值可以使⽤逗号分割。
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

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