讀取自定義yml文件與屬性


在網上找了很多種讀取自定義yml文件與屬性的東西,大部分都要定義實體類字段與配置文件中屬性對應,新加屬性或編輯自定義屬性名會很麻煩,下面的方法只需要使用注解@value即可

1.首先寫配置文件,用來讀取yml文件 2.

 1 package com.gd.ctripbusiness.config;
 2 
 3 import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
 4 import org.springframework.core.env.PropertiesPropertySource;
 5 import org.springframework.core.env.PropertySource;
 6 import org.springframework.core.io.support.EncodedResource;
 7 import org.springframework.core.io.support.PropertySourceFactory;
 8 
 9 import java.io.FileNotFoundException;
10 import java.io.IOException;
11 import java.util.Properties;
12 
13 
14 public class YamlPropertySourceFactory implements PropertySourceFactory {
15 
16     @Override
17     public PropertySource< ? > createPropertySource(String name, EncodedResource resource) throws IOException {
18         Properties propertiesFromYaml = loadYamlIntoProperties(resource);
19         String sourceName = name != null ? name : resource.getResource().getFilename();
20         return new PropertiesPropertySource(sourceName, propertiesFromYaml);
21     }
22 
23     private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
24         try {
25             YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
26             factory.setResources(resource.getResource());
27             factory.afterPropertiesSet();
28             return factory.getObject();
29         } catch (IllegalStateException e) {
30             Throwable cause = e.getCause();
31             if (cause instanceof FileNotFoundException) {
32                 throw (FileNotFoundException) e.getCause();
33             }
34             throw e;
35         }
36     }
37 
38 
39 }

2.啟動類加上自定義的的yml文件

 

 

@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:xxx.yml")

 

3.在使用的時候用@value注解即可

 

 

 

 @Value("${ccbb.des.a}")
    public String as1;

 

參考文章: https://blog.csdn.net/zxl8899/article/details/106382719


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM