欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中5種高大上的yml文件讀取方式

 更新時(shí)間:2022年03月08日 11:05:23   作者:碼農(nóng)參上  
本文主要介紹了SpringBoot中5種高大上的yml文件讀取方式,總結(jié)一下除了@Value和@ConfigurationProperties外,還能夠通過哪些方式,來讀取yml配置文件的內(nèi)容,感興趣的可以了解一下

上一篇文章中,我們從源碼角度分析了SpringBoot解析yml配置文件的全流程,那么我們今天就來點(diǎn)實(shí)戰(zhàn),總結(jié)一下除了爛大街的@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)容:

susan
female
{person2.age=18, person2.gender=female, person2.name=susan}

但是這樣的使用中有一個(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中的屬性:

susan
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=susan, 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é)果:

susan
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: susan
  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=susan, gender=female}}

接下來看一下loadAll方法,它可以用來加載yml中使用---連接符連接的多個(gè)文檔,將上面的yml文件進(jìn)行修改:

person1:
  name: hydra
  gender: male
---
person2:
  name: susan
  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=susan, 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=susan, 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=susan, gender=female))

SnakeYml其實(shí)實(shí)現(xiàn)了非常多的功能,這里就不一一列舉了,有興趣的小伙伴可以自己查看一下文檔。如果你看了上一篇的文章后跟著翻閱了一下源碼,那么你會(huì)發(fā)現(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=susan, 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),各自具備一些特殊的用法,而我們?cè)诠ぷ髦懈嗲闆r下,要根據(jù)具體的用途進(jìn)行一種方案的選取或多種的搭配使用。

到此這篇關(guān)于SpringBoot中5種高大上的yml文件讀取方式的文章就介紹到這了,更多相關(guān)SpringBoot yml文件讀取方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Springboot整合Shiro實(shí)現(xiàn)登錄與權(quán)限校驗(yàn)詳細(xì)解讀

    Springboot整合Shiro實(shí)現(xiàn)登錄與權(quán)限校驗(yàn)詳細(xì)解讀

    本文給大家介紹Springboot整合Shiro的基本使用,Apache?Shiro是Java的一個(gè)安全框架,Shiro本身無法知道所持有令牌的用戶是否合法,我們將整合Shiro實(shí)現(xiàn)登錄與權(quán)限的驗(yàn)證
    2022-04-04
  • springBoot熱部署、請(qǐng)求轉(zhuǎn)發(fā)與重定向步驟詳解

    springBoot熱部署、請(qǐng)求轉(zhuǎn)發(fā)與重定向步驟詳解

    這篇文章主要介紹了springBoot熱部署、請(qǐng)求轉(zhuǎn)發(fā)與重定向,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-06-06
  • 簡(jiǎn)單談?wù)凧VM、JRE和JDK的區(qū)別與聯(lián)系

    簡(jiǎn)單談?wù)凧VM、JRE和JDK的區(qū)別與聯(lián)系

    簡(jiǎn)單的說JDK是用于開發(fā)的而JRE是用于運(yùn)行Java程序的。JDK和JRE都包含了JVM,從而使得我們可以運(yùn)行Java程序。JVM是Java編程語言的核心并且具有平臺(tái)獨(dú)立性。
    2016-05-05
  • java實(shí)現(xiàn)JSON字符串格式化輸出

    java實(shí)現(xiàn)JSON字符串格式化輸出

    這篇文章主要為大家詳細(xì)介紹了如何使用java實(shí)現(xiàn)JSON字符串格式化輸出,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解下
    2024-01-01
  • Java如何處理圖片保存之后變紅色的問題

    Java如何處理圖片保存之后變紅色的問題

    這篇文章主要介紹了Java如何處理圖片保存之后變紅色的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Maven項(xiàng)目修改JDK版本全過程

    Maven項(xiàng)目修改JDK版本全過程

    這篇文章主要介紹了Maven項(xiàng)目修改JDK版本全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java Swing null絕對(duì)布局的實(shí)現(xiàn)示例

    Java Swing null絕對(duì)布局的實(shí)現(xiàn)示例

    這篇文章主要介紹了Java Swing null絕對(duì)布局的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Java基礎(chǔ)之位運(yùn)算知識(shí)總結(jié)

    Java基礎(chǔ)之位運(yùn)算知識(shí)總結(jié)

    最近接觸到了java位運(yùn)算,之前對(duì)位運(yùn)算的了解僅僅停留在表現(xiàn)結(jié)果上,乘2除以2,對(duì)背后的原理并不了解,現(xiàn)在學(xué)習(xí)記錄一下,需要的朋友可以參考下
    2021-05-05
  • 基于Java回顧之JDBC的使用詳解

    基于Java回顧之JDBC的使用詳解

    本篇文章是對(duì)Java中JDBC的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • Java泛型機(jī)制的程序演示詳解

    Java泛型機(jī)制的程序演示詳解

    這篇文章主要為大家詳細(xì)介紹了Java泛型機(jī)制的程序演示,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08

最新評(píng)論