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

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

@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等其他格式的文件需要自定義實現。

一、@Value註解讀取文件

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

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

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

@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文件,然後在註解

@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)

二、Environment讀取文件

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

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

三、@ConfigurationProperties讀取配置文件

@ConfigurationProperties可以將配置文件直接映射成一個實體類,然後我們可以直接操作實體類來獲取配置文件相關數據。

新建一個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集合,則做以下修改即可。

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