如何讀取properties或yml文件數(shù)據(jù)并匹配
讀取properties或yml文件數(shù)據(jù)并匹配
使用springboot獲取配置的文件的數(shù)據(jù)有多種方式,其中是通過注解@Value,此處通過IO獲取配置文件內(nèi)容。
此前已經(jīng)在另外的test.xml文件中的bean中可設(shè)置xx或yy,這里實(shí)現(xiàn)如果test.xml文件中沒有設(shè)置,可在application.*文件中進(jìn)行設(shè)置。
如下:
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("application.properties");
if(stream == null){
stream = getClass().getClassLoader().getResourceAsStream("application.yml");
InputStreamReader in = new InputStreamReader(stream, "gbk");
BufferedReader reader = new BufferedReader(in);
String line;
while ((line = reader.readLine()) != null) {
if(line.trim().split(":")[0].contentEquals("xx")){
//在test.xml中讀取后可通過set傳值。這里也可以自己通過設(shè)置相應(yīng)參數(shù)的set方法進(jìn)行傳值
this.setXX(line.trim().split(":")[1].trim());
}else if(line.trim().split(":")[0].contentEquals("yy")){
this.setYY(line.trim().split(":")[1].trim());
}
}
}else{
InputStreamReader in = new InputStreamReader(stream, "gbk");
BufferedReader reader = new BufferedReader(in);
String line;
while ((line = reader.readLine()) != null) {
if(line.trim().split("=")[0].contentEquals("xx")){
//在test.xml中讀取后可通過set傳值。這里也可以自己通過設(shè)置相應(yīng)參數(shù)的set方法進(jìn)行傳值
this.setXX(line.trim().split(":")[1].trim());
}else if(line.trim().split("=")[0].contentEquals("yy")){
this.setYY(line.trim().split(":")[1].trim());
}
}
}
} catch (FileNotFoundException e) {
logger.error("無法找到application.*文件",e);
} catch (IOException e) {
logger.error("讀取配置文件的ip或port有問題",e);
}
讀取yml,properties配置文件幾種方式小結(jié)
1-@value
@Value("${keys}")
private String key;
這里需要注意的是
- 當(dāng)前類要交給spring來管理
- @Value不會(huì)賦值給static修飾的變量。
因?yàn)镾pring的@Value依賴注入是依賴set方法,而自動(dòng)生成的set方法是普通的對(duì)象方法,你在普通的對(duì)象方法里,都是給實(shí)例變量賦值的,不是給靜態(tài)變量賦值的,static修飾的變量,一般不生成set方法。若必須給static修飾的屬性賦值可以參考以下方法
private static String url;
// 記得去掉static
@Value("${mysql.url}")
public void setDriver(String url) {
JdbcUtils.url= url;
}
但是該方案有個(gè)弊端,數(shù)組應(yīng)該如何注入呢?
2-使用對(duì)象注入
auth:
clients:
- id:1
password: 123
- id: 2
password: 123
@Component
@ConfigurationProperties(prefix="auth")
public class IgnoreImageIdConfig {
private List<Map<String,String>> clients =new ArrayList<Integer>();
}
利用配置Javabean的形式來獲得值,值得注意的是,對(duì)象里面的引用名字(‘clients'),必須和yml文件中的(‘clients')一致,不然就會(huì)取不到數(shù)據(jù),另外一點(diǎn)是,數(shù)組這個(gè)對(duì)象必須先new出來,如果沒有對(duì)象的話也會(huì)取值失敗的,(同理map形式也必須先將map對(duì)應(yīng)的對(duì)象new出來)。
3-讀取配置文件
private static final String FILE_PATH = "classpath:main_data_sync.yml";
static Map<String, String> result = null;
private static Properties properties = null;
private YmlUtil() {
}
/**
* 讀取yml的配置文件數(shù)據(jù)
* @param filePath
* @param keys
* @return
*/
public static Map<String, String> getYmlByFileName(String filePath, String... keys) {
result = new HashMap<>(16);
if (filePath == null) {
filePath = FILE_PATH;
}
InputStream in = null;
File file = null;
try {
file = ResourceUtils.getFile(filePath);
in = new BufferedInputStream(new FileInputStream(file));
Yaml props = new Yaml();
Object obj = props.loadAs(in, Map.class);
Map<String, Object> param = (Map<String, Object>) obj;
for (Map.Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (keys.length != 0 && !keys[0].equals(key)) {
continue;
}
if (val instanceof Map) {
forEachYaml(key, (Map<String, Object>) val, 1, keys);
} else {
String value = val == null ? null : JSONObject.toJSONString(val);
result.put(key, value);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return result;
}
public static Map<String, String> forEachYaml(String keyStr, Map<String, Object> obj, int i, String... keys) {
for (Map.Entry<String, Object> entry : obj.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (keys.length > i && !keys[i].equals(key)) {
continue;
}
String strNew = "";
if (StringUtils.isNotEmpty(keyStr)) {
strNew = keyStr + "." + key;
} else {
strNew = key;
}
if (val instanceof Map) {
forEachYaml(strNew, (Map<String, Object>) val, ++i, keys);
i--;
} else {
String value = val == null ? null : JSONObject.toJSONString(val);
result.put(strNew, value);
}
}
return result;
}
/**
* 獲取Properties類型屬性值
* @param filePath classpath:文件名
* @param key key值
* @return
* @throws IOException
*/
public static String getProperties(String filePath,String key) throws IOException {
if (properties == null) {
Properties prop = new Properties();
//InputStream in = Util.class.getClassLoader().getResourceAsStream("testUrl.properties");
InputStream in = new BufferedInputStream(new FileInputStream(ResourceUtils.getFile(filePath))) ;
prop.load(in);
properties = prop;
}
return properties.getProperty(key);
}
public static void main(String[] args) {
/*Map<String, String> cId = getYmlByFileName("classpath:test.yml", "auth", "clients");
//cId.get("")
String json = cId.get("auth.clients");
List<Map> maps = JSONObject.parseArray(json, Map.class);
System.out.println(maps);*/
try {
String properties = getProperties("classpath:test.properties", "fileServerOperator.beanName");
System.out.println(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
auth: #認(rèn)證
clients:
- id: 1
secretKey: ba2631ee44149bbe #密鑰key
- id: 2
secretKey: ba2631ee44149bbe #密鑰key
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot+zookeeper實(shí)現(xiàn)分布式鎖的示例代碼
本文主要介紹了springboot+zookeeper實(shí)現(xiàn)分布式鎖的示例代碼,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
SpringData整合ElasticSearch實(shí)現(xiàn)CRUD的示例代碼(超詳細(xì))
本文主要介紹了SpringData整合ElasticSearch實(shí)現(xiàn)CRUD的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
前端如何傳遞Array、Map類型數(shù)據(jù)到Java后端
這篇文章主要給大家介紹了關(guān)于前端如何傳遞Array、Map類型數(shù)據(jù)到Java后端的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01
java實(shí)現(xiàn)單鏈表中是否有環(huán)的方法詳解
本篇文章介紹了,用java實(shí)現(xiàn)單鏈表中是否有環(huán)的方法詳解。需要的朋友參考下2013-05-05
JUC循環(huán)屏障CyclicBarrier與CountDownLatch區(qū)別詳解
這篇文章主要為大家介紹了JUC循環(huán)屏障CyclicBarrier與CountDownLatch區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
Springboot2.0配置JPA多數(shù)據(jù)源連接兩個(gè)mysql數(shù)據(jù)庫方式
這篇文章主要介紹了Springboot2.0配置JPA多數(shù)據(jù)源連接兩個(gè)mysql數(shù)據(jù)庫方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
深入學(xué)習(xí)Spring Cloud-Ribbon
這篇文章主要介紹了Spring Cloud-Ribbon的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友一起看看吧2021-03-03
Redisson延遲隊(duì)列執(zhí)行流程源碼解析
這篇文章主要為大家介紹了Redisson延遲隊(duì)列執(zhí)行流程源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09

