Java開發(fā)日記之你會(huì)不會(huì)5種牛的yml文件讀取方式
前言
除了爛大街的@Value
和@ConfigurationProperties
外,還能夠通過哪些方式,來讀取yml配置文件的內(nèi)容?
1、Environment
在Spring中有一個(gè)類Environment
,它可以被認(rèn)為是當(dāng)前應(yīng)用程序正在運(yùn)行的環(huán)境,它繼承了PropertyResolver
接口,因此可以作為一個(gè)屬性解析器使用。先創(chuàng)建一個(gè)yml文件,屬性如下:
person: name: hydra gender: male age: 18
使用起來也非常簡(jiǎn)單,直接使用@Autowired
就可以注入到要使用的類中,然后調(diào)用它的getProperty()
方法就可以根據(jù)屬性名稱取出對(duì)應(yīng)的值了。
@RestController public class EnvironmentController { @Autowired private Environment environment; @GetMapping("envTest") private void getEnv(){ System.out.println(environment.getProperty("person.name")); System.out.println(environment.getProperty("person.gender")); Integer autoClose = environment .getProperty("person.age", Integer.class); System.out.println(autoClose); String defaultValue = environment .getProperty("person.other", String.class, "defaultValue"); System.out.println(defaultValue); } }
在上面的例子中可以看到,除了簡(jiǎn)單的獲取外,Environment
提供的方法還可以對(duì)取出的屬性值進(jìn)行類型轉(zhuǎn)換、以及默認(rèn)值的設(shè)置,調(diào)用一下上面的接口,打印結(jié)果如下:
hydra male 18 defaultValue
除了獲取屬性外,還可以用來判斷激活的配置文件,先在application.yml中激活pro文件:
spring: profiles: active: pro
可以通過acceptsProfiles
方法來檢測(cè)某一個(gè)配置文件是否被激活加載,或者通過getActiveProfiles
方法拿到所有被激活的配置文件。測(cè)試接口:
@GetMapping("getActiveEnv") private void getActiveEnv(){ System.out.println(environment.acceptsProfiles("pro")); System.out.println(environment.acceptsProfiles("dev")); String[] activeProfiles = environment.getActiveProfiles(); for (String activeProfile : activeProfiles) { System.out.println(activeProfile); } }
打印結(jié)果:
true
false
pro
2、YamlPropertiesFactoryBean
在Spring中還可以使用YamlPropertiesFactoryBean
來讀取自定義配置的yml文件,而不用再被拘束于application.yml及其激活的其他配置文件。
在使用過程中,只需要通過setResources()
方法設(shè)置自定義yml配置文件的存儲(chǔ)路徑,再通過getObject()
方法獲取Properties
對(duì)象,后續(xù)就可以通過它獲取具體的屬性,下面看一個(gè)例子:
@GetMapping("fcTest") public void ymlProFctest(){ YamlPropertiesFactoryBean yamlProFb = new YamlPropertiesFactoryBean(); yamlProFb.setResources(new ClassPathResource("application2.yml")); Properties properties = yamlProFb.getObject(); System.out.println(properties.get("person2.name")); System.out.println(properties.get("person2.gender")); System.out.println(properties.toString()); }
查看運(yùn)行結(jié)果,可以讀取指定的application2.yml的內(nèi)容:
fcant female {person2.age=18, person2.gender=female, person2.name=fcant}
但是這樣的使用中有一個(gè)問題,那就是只有在這個(gè)接口的請(qǐng)求中能夠取到這個(gè)屬性的值,如果再寫一個(gè)接口,不使用YamlPropertiesFactoryBean
讀取配置文件,即使之前的方法已經(jīng)讀取過這個(gè)yml文件一次了,第二個(gè)接口取到的仍然還是空值。來對(duì)這個(gè)過程進(jìn)行一下測(cè)試:
@Value("${person2.name:null}") private String name; @Value("${person2.gender:null}") private String gender; @GetMapping("fcTest2") public void ymlProFctest2(){ System.out.println(name); System.out.println(gender); }
先調(diào)用一次fcTest
接口,再調(diào)用fcTest2
接口時(shí)會(huì)打印null
值:
null null
想要解決這個(gè)問題也很簡(jiǎn)單,可以配合PropertySourcesPlaceholderConfigurer
使用,它實(shí)現(xiàn)了BeanFactoryPostProcessor
接口,也就是一個(gè)bean工廠后置處理器的實(shí)現(xiàn),可以將配置文件的屬性值加載到一個(gè)Properties
文件中。使用方法如下:
@Configuration public class PropertyConfig { @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yamlProFb = new YamlPropertiesFactoryBean(); yamlProFb.setResources(new ClassPathResource("application2.yml")); configurer.setProperties(yamlProFb.getObject()); return configurer; } }
再次調(diào)用之前的接口,結(jié)果如下,可以正常的取到application2.yml中的屬性:
fcant female
除了使用YamlPropertiesFactoryBean
將yml解析成Properties
外,其實(shí)還可以使用YamlMapFactoryBean
解析yml成為Map
,使用方法非常類似:
@GetMapping("fcMapTest") public void ymlMapFctest(){ YamlMapFactoryBean yamlMapFb = new YamlMapFactoryBean(); yamlMapFb.setResources(new ClassPathResource("application2.yml")); Map<String, Object> map = yamlMapFb.getObject(); System.out.println(map); }
打印結(jié)果:
{person2={name=fcant, gender=female, age=18}}
3、監(jiān)聽事件
SpringBoot是通過監(jiān)聽事件的方式來加載和解析的yml文件,那么也可以仿照這個(gè)模式,來加載自定義的配置文件。
首先,定義一個(gè)類實(shí)現(xiàn)ApplicationListener
接口,監(jiān)聽的事件類型為ApplicationEnvironmentPreparedEvent
,并在構(gòu)造方法中傳入要解析的yml文件名:
public class YmlListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { private String ymlFilePath; public YmlListener(String ymlFilePath){ this.ymlFilePath = ymlFilePath; } //... }
自定義的監(jiān)聽器中需要實(shí)現(xiàn)接口的onApplicationEvent()
方法,當(dāng)監(jiān)聽到ApplicationEnvironmentPreparedEvent
事件時(shí)會(huì)被觸發(fā):
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); ResourceLoader loader = new DefaultResourceLoader(); YamlPropertySourceLoader ymlLoader = new YamlPropertySourceLoader(); try { List<PropertySource<?>> sourceList = ymlLoader .load(ymlFilePath, loader.getResource(ymlFilePath)); for (PropertySource<?> propertySource : sourceList) { environment.getPropertySources().addLast(propertySource); } } catch (IOException e) { e.printStackTrace(); } }
上面的代碼中,主要實(shí)現(xiàn)了:
- 獲取當(dāng)前環(huán)境
Environment
,當(dāng)ApplicationEnvironmentPreparedEvent
事件被觸發(fā)時(shí),已經(jīng)完成了Environment
的裝載,并且能夠通過event
事件獲取 - 通過
YamlPropertySourceLoader
加載、解析配置文件 - 將解析完成后的
OriginTrackedMapPropertySource
添加到Environment
中
修改啟動(dòng)類,在啟動(dòng)類中加入這個(gè)監(jiān)聽器:
public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.addListeners(new YmlListener("classpath:/application2.yml")); application.run(args); }
在向environment
中添加propertySource
前加一個(gè)斷點(diǎn),查看環(huán)境的變化。
執(zhí)行完成后,可以看到配置文件源已經(jīng)被添加到了環(huán)境中。
啟動(dòng)完成后再調(diào)用一下接口,查看結(jié)果:
Fcant female
能夠正確的取到配置文件中的值,說明自定義的監(jiān)聽器已經(jīng)生效。
4、SnakeYml
前面介紹的幾種方式,在Spring環(huán)境下無需引入其他依賴就可以完成的,接下來要介紹的SnakeYml在使用前需要引入依賴,但是同時(shí)也可以脫離Spring環(huán)境單獨(dú)使用。先引入依賴坐標(biāo):
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.23</version> </dependency>
準(zhǔn)備一個(gè)yml配置文件:
person1: name: hydra gender: male person2: name: fcant gender: female
在使用SnakeYml
解析yml時(shí),最常使用的就是load
、loadlAll
、loadAs
方法,這三個(gè)方法可以加載yml文件或字符串,最后返回解析后的對(duì)象。先從基礎(chǔ)的load
方法開始演示:
public void test1(){ Yaml yaml=new Yaml(); Map<String, Object> map = yaml.load(getClass().getClassLoader() .getResourceAsStream("snake1.yml")); System.out.println(map); }
運(yùn)行上面的代碼,打印Map中的內(nèi)容:
{person1={name=hydra, gender=male}, person2={name=fcant, gender=female}}
接下來看一下loadAll方法,它可以用來加載yml中使用—-連接符連接的多個(gè)文檔,將上面的yml文件進(jìn)行修改:
person1: name: hydra gender: male --- person2: name: fcant gender: female
在添加了連接符后,嘗試再使用load
方法進(jìn)行解析,報(bào)錯(cuò)顯示發(fā)現(xiàn)了另一段yml文檔從而無法正常解析。
這時(shí)候修改上面的代碼,使用loadAll
方法:
public void test2(){ Yaml yaml=new Yaml(); Iterable<Object> objects = yaml.loadAll(getClass().getClassLoader() .getResourceAsStream("snake2.yml")); for (Object object : objects) { System.out.println(object); } }
執(zhí)行結(jié)果如下:
{person1={name=hydra, gender=male}} {person2={name=fcant, gender=female}}
可以看到,loadAll
方法返回的是一個(gè)對(duì)象的迭代,里面的每個(gè)對(duì)象對(duì)應(yīng)yml中的一段文檔,修改后的yml文件就被解析成了兩個(gè)獨(dú)立的Map。
接下來再來看一下loadAs
方法,它可以在yml解析過程中指定類型,直接封裝成一個(gè)對(duì)象。直接復(fù)用上面的snake1.yml,在解析前先創(chuàng)建兩個(gè)實(shí)體類對(duì)象用于接收:
@Data public class Person { SinglePerson person1; SinglePerson person2; } @Data public class SinglePerson { String name; String gender; }
下面使用loadAs
方法加載yml,注意方法的第二個(gè)參數(shù),就是用于封裝yml的實(shí)體類型。
public void test3(){ Yaml yaml=new Yaml(); Person person = yaml.loadAs(getClass().getClassLoader(). getResourceAsStream("snake1.yml"), Person.class); System.out.println(person.toString()); }
查看執(zhí)行結(jié)果:
Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))
實(shí)際上,如果想要將yml封裝成實(shí)體對(duì)象,也可以使用另一種方法。在創(chuàng)建Yaml對(duì)象的時(shí)候,傳入一個(gè)指定實(shí)體類的構(gòu)造器對(duì)象,然后直接調(diào)用load
方法就可以實(shí)現(xiàn):
public void test4(){ Yaml yaml=new Yaml(new Constructor(Person.class)); Person person = yaml.load(getClass().getClassLoader(). getResourceAsStream("snake1.yml")); System.out.println(person.toString()); }
執(zhí)行結(jié)果與上面相同:
Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))
SnakeYml其實(shí)實(shí)現(xiàn)了非常多的功能,這里就不一一列舉了,有興趣的小伙伴可以自己查看一下文檔。其實(shí)在SpringBoot的底層,也是借助了SnakeYml來進(jìn)行的yml的解析操作。
5、jackson-dataformat-yaml
相比大家平常用jackson比較多的場(chǎng)景是用它來處理json,其實(shí)它也可以用來處理yml,使用前需要引入依賴:
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.12.3</version> </dependency>
使用jackson讀取yml也非常簡(jiǎn)單,這里用到了常用的ObjectMapper
,在創(chuàng)建ObjectMapper
對(duì)象時(shí)指定使用YAML工廠,之后就可以簡(jiǎn)單的將yml映射到實(shí)體:
public void read() throws IOException { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); InputStream input = new FileInputStream("F:\\Work\\yml\\src\\main\\resources\\snake1.yml"); Person person = objectMapper.readValue(input, Person.class); System.out.println(person.toString()); }
運(yùn)行結(jié)果:
Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))
如果想要生成yml文件的話,可以調(diào)用ObjectMapper
的writeValue
方法實(shí)現(xiàn):
public void write() throws IOException { Map<String,Object> map=new HashMap<>(); SinglePerson person1 = new SinglePerson("Trunks", "male"); SinglePerson person2 = new SinglePerson("Goten", "male"); Person person=new Person(person1,person2); map.put("person",person); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); objectMapper .writeValue(new File("F:\\Work\\yml\\src\\main\\resources\\jackson-gen.yml"),map); }
查看生成的yml文件,可以看到j(luò)ackson對(duì)字符串類型嚴(yán)格的添加了引號(hào),還在文檔的開頭添加了yml的鏈接符。至于其他jackson讀寫yml的復(fù)雜功能,可以在工作中自己去探索使用。
總結(jié)
這里介紹了5種讀取yml配置文件的方式,前3種依賴于Spring環(huán)境,而SnakeYml
和Jackson
則可以脫離環(huán)境獨(dú)立使用,可以說它們是對(duì)@Value
和@ConfigurationProperties
注解使用的補(bǔ)充。這幾種方法的使用場(chǎng)景不同,也各有各的有優(yōu)點(diǎn),各自具備一些特殊的用法,而在工作中更多情況下,要根據(jù)具體的用途進(jìn)行一種方案的選取或多種的搭配使用。
到此這篇關(guān)于Java開發(fā)日記之你會(huì)不會(huì)5種牛的yml文件讀取方式的文章就介紹到這了,更多相關(guān)Java yml文件讀取方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java如何利用poi解析doc和docx中的數(shù)據(jù)
這篇文章主要給大家介紹了關(guān)于java如何利用poi解析doc和docx中數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04Springboot mybatis-plus配置及用法詳解
這篇文章主要介紹了Springboot mybatis-plus配置及用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Java結(jié)合redistemplate使用分布式鎖案例講解
在Java中使用RedisTemplate結(jié)合Redis來實(shí)現(xiàn)分布式鎖是一種常見的做法,特別適用于微服務(wù)架構(gòu)或多實(shí)例部署的應(yīng)用程序中,以確保數(shù)據(jù)的一致性和避免競(jìng)態(tài)條件,下面給大家分享使用Spring Boot和RedisTemplate實(shí)現(xiàn)分布式鎖的案例,感興趣的朋友一起看看吧2024-08-08java 使用ImageIO.writer從BufferedImage生成jpeg圖像遇到問題總結(jié)及解決
這篇文章主要介紹了java 使用ImageIO.writer從BufferedImage生成jpeg圖像遇到問題總結(jié)及解決的相關(guān)資料,需要的朋友可以參考下2017-03-03Java進(jìn)階之高并發(fā)核心Selector詳解
前幾篇文章介紹了Java高并發(fā)的一些基礎(chǔ)內(nèi)容,認(rèn)識(shí)了Channel,Buffer和Selector的基本用法,有了感性認(rèn)識(shí)之后,來看看Selector的底層是如何實(shí)現(xiàn)的。,需要的朋友可以參考下2021-05-05Java 如何讀取Excel格式xls、xlsx數(shù)據(jù)工具類
這篇文章主要介紹了Java 如何讀取Excel格式xls、xlsx數(shù)據(jù)工具類的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Java的MyBatis框架中MyBatis Generator代碼生成器的用法
這篇文章主要介紹了Java的MyBatis框架中Mybatis Generator代碼生成器的用法,Mybatis Generator主要被用來生成繁瑣的配置文件來提高效率,需要的朋友可以參考下2016-04-04java本機(jī)內(nèi)存分配Native?memory?allocation?mmap失敗問題解決
這篇文章主要介紹了java本機(jī)內(nèi)存分配Native?memory?allocation?mmap失敗問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11