本篇內容主要講解“使用@Value注解從配置文件中讀取數組的方法”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“使用@Value注解從配置文件中讀取數組的方法”吧!
作用:從配置文件中取值
用法:
(1)configuration.properties配置
status.notice.switch=open
(2)java文件自動注入
@Value("${status.notice.switch}")
private String statusNoticeSwitch;(1)configuration.properties配置
lanwon.hospital.id=43534,234543,w353654
(2)java文件自動注入
@Value("#{'${lanwon.hospital.id}'.split(',')}")
private List<String> hospitalIdList;在 Spring 組件中使用 @Value 注解的方式,可以直接從 .properties,.yum 等配置文件獲取配置信息便于實現項目的配置化運行。
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.1 聲明的變量
public static class FieldValueTestBean {
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;
}2.2 setter 方法
public static class PropertyValueTestBean {
private String defaultLocale;
@Value("#{ systemProperties['user.region'] }")
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['user.region'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}
// ...
}2.4 構造方法
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.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;到此,相信大家對“使用@Value注解從配置文件中讀取數組的方法”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。