spring-boot-route(二)讀取配置文件的幾種方式

Spring Boot提供了兩種格式的配置文件,分別是propertiesyml。Spring Boot最大的特色就是自動化配置,若是咱們想修改自動化配置的默認值,就能夠經過配置文件來指定本身服務器相關的參數。java

配置文件集約管理了配置信息,若是把配置參數寫到Java代碼中,維護起來很是不方便,若是使用配置文件,咱們能夠統一管理,統一修改。我比較推薦使用yml格式的配置文件,YAML是專門用來寫配置文件的語言,一般以yml爲後綴,它的結構很是清晰,更易於閱讀。git

將自定義的配置寫在配置文件中後,若是想要在java代碼中使用配置,這時候就須要讀取配置文件,讀取配置文件的方式有三種,咱們挨個介紹一下若是進行讀取!github

第一種:使用@Value註解讀取

第一步:在配置文件中增長加入如下配置spring

config:
  name: Java旅途
  desc: spring-boot-route

第二部:新建Java類讀取配置信息數組

@RestController
public class GetValue {

    @Value("${config.name}")
    private String name;

    @Value("${config.desc}")
    private String desc;

    @GetMapping("getValue")
    public String getValue(){
        return "name="+name+";desc="+desc;
    }
}

@Value註解使用簡單,適合單個參數的注入。服務器

第二種:使用@ConfigurationProperties讀取

@ConfigurationProperties與@Value相比,更加適合讀取數組類型的參數。微信

1. 獲取單個對象

第一步:在yml文件中新建對象類型的配置信息app

configs:
  config:
    name: Java旅途
    desc: spring-boot-route

第二步:新建實體映射配置信息ide

@Component
@ConfigurationProperties(prefix = "configs.config")
@Data
public class Config {

    private String name;
    private String desc;
}

第三步:新建類測試是否獲取到參數spring-boot

@RestController
public class GetConfigurationProperties {

    @Autowired
    private Config config;

    @GetMapping("/getConfig")
    public String getConfig(){
        return config.getName()+";"+config.getDesc();
    }
}

2. 獲取對象集合

第一步:在yml文件中新建數組類型的參數

configs:
  config:
    - name: Java旅途
      desc: spring-boot-route
    - name: javatrip
      desc: spring-boot-yml

第二步:新建實體映射配置信息

@Component
@ConfigurationProperties(prefix = "configarr")
@Data
public class Configs {

    private List<Config> config = new ArrayList<>();

    @Data
    public static class Config{

        private String name;
        private String desc;
    }
}

第三步:新建測試類獲取參數

@RestController
public class GetConfigurationProperties {

    @Autowired
    private Configs configs;
    
    @GetMapping("/getConfigs")
    public String getConfigs(){

        String content = "";
        List<Configs.Config> configList = configs.getConfig();
        Map<String,Object> map = new HashMap<>();
        for (Configs.Config bean : configList){
            content += bean.getName()+";"+bean.getDesc()+",";
        }
        return content;
    }
}

除了上面介紹的兩種方式以外,還能夠經過Spring Boot上下文的環境變量來讀取配置文件信息,不過上面兩種方式已經徹底能夠知足全部需求,這裏就再也不進行介紹了。

思考與擴展

若是多個配置文件具備相同的配置信息,那麼如何讀取特定的配置文件信息呢

配置文件具備優先級,通常狀況下,yml文件的優先級高於properties,這樣就會致使properties的配置信息後加載,最後讀取的時候就會properties的配置信息的優先級會更高。

上面介紹的兩種讀取配置文件的方式能夠和另外一個註解配合使用,@PropertySource經常使用的三個屬性,一個是value用於指定配置文件,另外一個是encoding用於指定編碼,最後一個是factory,用於指定解析工廠。

這裏須要注意一下:@PropertySource默認只會加載properties格式的文件,也就是咱們若是指定了yml類型的文件是不會生效的,這時候就須要咱們重寫解析工廠。

先看看下默認的解析工廠源碼:

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

自定義解析工廠,實現PropertySourceFactory

public class YmlConfigFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

第一步:新建兩個配置文件,test.yml和test.properties,增長如下配置信息

spring:
  value: javatrip123
  remark: javatrip123
spring:
  value: javatrip123
  remark: javatrip123

第二步:指定配置文件映射配置文件內容

@Data
@Configuration
@PropertySource(value = {"classpath:test.yml"},encoding = "gbk")
@ConfigurationProperties(prefix = "spring")
public class Spring {

    private String value;
    private String remark;
}

第三步:新建類進行測試

@RestController
public class GetSource {

    @Autowired
    private Spring spring;

    @GetMapping("get")
    public String getSource(){
        return spring.getRemark()+";"+spring.getValue();
    }
}

此是spring-boot-route系列的第二篇文章,這個系列的文章都比較簡單,主要目的就是爲了幫助初次接觸Spring Boot 的同窗有一個系統的認識。本文已收錄至個人github,歡迎各位小夥伴star

githubhttps://github.com/binzh303/s...

點關注、不迷路

若是以爲文章不錯,歡迎關注點贊收藏,大家的支持是我創做的動力,感謝你們。

若是文章寫的有問題,請不要吝嗇,歡迎留言指出,我會及時覈查修改。

若是你還想更加深刻的瞭解我,能夠微信搜索「Java旅途」進行關注。回覆「1024」便可得到學習視頻及精美電子書。天天7:30準時推送技術文章,讓你的上班路不在孤獨,並且每個月還有送書活動,助你提高硬實力!

相關文章
相關標籤/搜索