Spring Boot讀取配置文件的幾種方式

Spring Boot獲取文件總的來講有三種方式,分別是@Value註解,@ConfigurationProperties註解和Environment接口。這三種註解能夠配合着@PropertySource來使用,@PropertySource主要是用來指定具體的配置文件。java

@PropertySource解析

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {

    String name() default "";

    String[] value();

    boolean ignoreResourceNotFound() default false;

    String encoding() default "";

    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}
  • value():指定配置文件
  • encoding():指定編碼,由於properties文件的編碼默認是ios8859-1,讀取出來是亂碼
  • factory():自定義解析文件類型,由於該註解默認只會加載properties文件,若是想要指定yml等其餘格式的文件須要自定義實現。

1、@Value註解讀取文件

新建兩個配置文件config.properties和configs.properties,分別寫入以下內容:ios

zhbin.config.web-configs.name=Java旅途
zhbin.config.web-configs.age=22
zhbin.config.web-configs.name=Java旅途
zhbin.config.web-configs.age=18

新增一個類用來讀取配置文件web

@Configuration
@PropertySource(value = {"classpath:config.properties"},encoding="gbk")
public class GetProperties {

    @Value("${zhbin.config.web-configs.name}")
    private String name;
    @Value("${zhbin.config.web-configs.age}")
    private String age;

    public String getConfig() {
        return name+"-----"+age;
    }
}

若是想要讀取yml文件,則咱們須要重寫DefaultPropertySourceFactory,讓其加載yml文件,而後在註解ide

@PropertySource上自定factory。代碼以下:編碼

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();
    }
}
@PropertySource(value = {"classpath:config.properties"},encoding="gbk",factory = YmlConfigFactory.class)

2、Environment讀取文件

配置文件咱們繼續用上面的兩個,定義一個類去讀取配置文件spa

@Configuration
@PropertySource(value = {"classpath:config.properties"},encoding="gbk")
public class GetProperties {

    @Autowired
    Environment environment;

    public String getEnvConfig(){
        String name = environment.getProperty("zhbin.config.web-configs.name");
        String age = environment.getProperty("zhbin.config.web-configs.age");
        return name+"-----"+age;
    }
}

3、@ConfigurationProperties讀取配置文件

@ConfigurationProperties能夠將配置文件直接映射成一個實體類,而後咱們能夠直接操做實體類來獲取配置文件相關數據。code

新建一個yml文件,固然properties文件也沒問題對象

zhbin:
  config:
    web-configs:
      name: Java旅途
      age: 20

新建實體類用來映射該配置接口

@Component
@ConfigurationProperties(prefix = "zhbin.config")
@Data
public class StudentYml {

    // webConfigs務必與配置文件相對應,寫爲駝峯命名方式
    private WebConfigs webConfigs = new WebConfigs();

    @Data
    public static class WebConfigs {
        private String name;
        private String age;
    }
}
  • prefix = "zhbin.config"用來指定配置文件前綴

若是須要獲取list集合,則作如下修改便可。get

zhbin:
  config:
    web-configs:
      - name: Java旅途
        age: 20
      - name: Java旅途2
        age: 202
@Component
@ConfigurationProperties(prefix = "zhbin.config")
@Data
public class StudentYml {

    private List<WebConfigs> webConfigs = new ArrayList<>();

    @Data
    public static class WebConfigs {

        private String name;
        private String age;
    }
}

經驗與坑

  • properties文件默認使用的是iso8859-1,而且不可修改
  • yml文件的加載順序高於properties,可是讀取配置信息的時候會讀取後加載的
  • @PropertySource註解默認只會加載properties文件
  • @PropertySource註解能夠與任何一種方式聯合使用
  • 簡單值推薦使用@Value,複雜對象推薦使用@ConfigurationProperties
相關文章
相關標籤/搜索