springboot02-YML的用法

二、配置文件

1.配置文件

  • Spring Boot使用的配置文件是:配置文件名是固定的:
    • application.properties。
    • application.yml。
    • 配置文件的作用是修改springboot的默認配置,比如端口號等配置。

.yml寫法:

#application.yml
server:
  port: 8086

.properties的寫法:

#application.properties
server.port=8085

2.YML語法:

1.基本語法

k:(空格)v:表示一對鍵值對(空格必須有);

空格的縮進來控制層次關機:只要左對齊的一列數據,都是同一個層次的;

2.值的寫法

字面量:普通的值(數字、字符串、布爾值)

​ k:v 字面直接寫即可;

​ 字符串默認情況下不用加上單引號和雙引號;

​ “” 雙引號:不會轉義字符串裏面的特殊字符;

​ ‘’ 單引號:會轉義特殊字符;

對象、Map

​ k:v

​ 對象的寫法:

friend:

​	last:1111

​	name:xiaowang

​	id:12345
friend: {last:11111,name:xiaowang,id:12345}

數組(list、set)

pets:
 - cat
 - dog
 - pig

pets: [cat,dog,pig]

3.yml文件在實際中的綁定使用(默認使用application.yml):

​ 1.首先創建bean的類class,與yml中的值一一對應

​ 2.給類上添加註解:

​ @Component

​ @ConfigurationProperties(value = “person”)

​ value是代表加載的哪一塊的值。

YML文件內容如下:

server:
  post: 8081

person:
  lastName: zhangsan
  age: 18
  brith: 2000/12/12
  boss: false
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - zhaoliu
    - wangsan
  Dog:
    name: 小狗
    age: 2

4.使用自定義yml文件加載

​ 對於自定義的yml文件,我們需要自己寫一個工廠類,因爲根據源碼:

@PropertySource註解只給出了properties的工廠類和application.yml的工廠類,如果我們不新建一個yml工廠類,那麼就無法得到yml中的配置信息。

自定義yml文件:

tm1.yml:

server:
  post: 8081

person:
  lastName: zhangsan
  age: 18
  brith: 2000/12/12
  boss: false
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - zhaoliu
    - wangsan
  Dog:
    name: 小狗
    age: 2

方法如下:

在person類前添加以下註解:

@Component

@PropertySource(value = {“classpath:tm1.yml”}, factory = YamlPropertySourceFactory.class)

@ConfigurationProperties(value = “person”)

YamlPropertySourceFactory:

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

這樣就可以得到自定義中的內容了

Controller寫法:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-AEwMdGeU-1583428325769)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\1583427714259.png)]

運行結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章