首頁  >  文章  >  Java  >  SpringBoot解析怎麼指定Yaml設定檔

SpringBoot解析怎麼指定Yaml設定檔

WBOY
WBOY轉載
2023-05-22 10:07:07884瀏覽

1、自訂設定檔

在resources下建立my.yaml文件,「-」用來表示陣列類型,一定要注意空格

my:
  contents:
    - id: 12121
      name: nadasd
    - id: 3333
      name: vfffff

2、配置物件類別

建立配置類別對象,在類別上新增@Component、@PropertySource、@ConfigurationProperties註解。

@Component是將該類別交由spring管理,@PropertySource用來指定設定檔及解析Yaml格式,@ConfigurationProperties是將解析後的設定檔屬性自動注入該類別的屬性。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@PropertySource(value = "classpath:my.yaml", factory = YamlPropertiesSourceFactory.class)
@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private List contents = new ArrayList<>();

    public List getContents() {
        return contents;
    }

    public void setContents(List contents) {
        this.contents = contents;
    }


}

class content {
    private String id;

    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@PropertySource註解是Spring用於載入設定文件,@PropertySource屬性如下:

  • name:預設為空,不指定Spring自動產生

  • value:設定檔

  • ignoreResourceNotFound:沒有找到設定檔是否忽略,預設false,4.0版本加入

  • #encoding:設定檔編碼格式,預設UTF-8 4.3版本才加入

  • factory:設定檔解析工廠,預設:PropertySourceFactory.class 4.3版本才加入,如果是之前的版本就需要手動注入設定檔解析Bean

Spring Boot 預設不支援@PropertySource讀取yaml 文件,需要自訂PropertySourceFactory進行解析。

3、YamlPropertiesSourceFactory

建立YamlPropertiesSourceFactory類別用來解析Yaml格式的檔案。

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class YamlPropertiesSourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        List> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
        return yamlSources.get(0);
    }

}

以上是SpringBoot解析怎麼指定Yaml設定檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除