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

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

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

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

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

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

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

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

@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文件中新建對象類型的配置信息緩存

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

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

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

    private String name;
    private String desc;
}

第三步:新建類測試是否獲取到參數微信

@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();
    }
}

本文示例代碼已上傳至github,點個star支持一下!

Spring Boot系列教程目錄

spring-boot-route(一)Controller接收參數的幾種方式

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

spring-boot-route(三)實現多文件上傳

spring-boot-route(四)全局異常處理

spring-boot-route(五)整合Swagger生成接口文檔

spring-boot-route(六)整合JApiDocs生成接口文檔

spring-boot-route(七)整合jdbcTemplate操做數據庫

spring-boot-route(八)整合mybatis操做數據庫

spring-boot-route(九)整合JPA操做數據庫

spring-boot-route(十)多數據源切換

spring-boot-route(十一)數據庫配置信息加密

spring-boot-route(十二)整合redis作爲緩存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

spring-boot-route(十五)整合RocketMQ

spring-boot-route(十六)使用logback生產日誌文件

spring-boot-route(十七)使用aop記錄操做日誌

spring-boot-route(十八)spring-boot-adtuator監控應用

spring-boot-route(十九)spring-boot-admin監控服務

spring-boot-route(二十)Spring Task實現簡單定時任務

spring-boot-route(二十一)quartz實現動態定時任務

spring-boot-route(二十二)實現郵件發送功能

spring-boot-route(二十三)開發微信公衆號

這個系列的文章都是工做中頻繁用到的知識,學完這個系列,應付平常開發綽綽有餘。若是還想了解其餘內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!

相關文章
相關標籤/搜索