Spring Boot获取文件总的来说有三种方式,分别是@Value注解,@ConfigurationProperties注解和Environment接口。这三种注解可以配合着@PropertySource来使用,@PropertySource主要是用来指定具体的配置文件。

@PropertySource解析

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Repeatable(PropertySources.class)
  5. public @interface PropertySource {
  6. String name() default "";
  7. String[] value();
  8. boolean ignoreResourceNotFound() default false;
  9. String encoding() default "";
  10. Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
  11. }
  • value():指定配置文件
  • encoding():指定编码,因为properties文件的编码默认是ios8859-1,读取出来是乱码
  • factory():自定义解析文件类型,因为该注解默认只会加载properties文件,如果想要指定yml等其他格式的文件需要自定义实现。

    一、@Value注解读取文件

    新建两个配置文件config.properties和configs.properties,分别写入如下内容:

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

    新增一个类用来读取配置文件

    1. @Configuration
    2. @PropertySource(value = {"classpath:config.properties"},encoding="gbk")
    3. public class GetProperties {
    4. @Value("${zhbin.config.web-configs.name}")
    5. private String name;
    6. @Value("${zhbin.config.web-configs.age}")
    7. private String age;
    8. public String getConfig() {
    9. return name+"-----"+age;
    10. }
    11. }

    如果想要读取yml文件,则我们需要重写DefaultPropertySourceFactory,让其加载yml文件,然后在注解
    @PropertySource上自定factory。代码如下:

    1. public class YmlConfigFactory extends DefaultPropertySourceFactory {
    2. @Override
    3. public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    4. String sourceName = name != null ? name : resource.getResource().getFilename();
    5. if (!resource.getResource().exists()) {
    6. return new PropertiesPropertySource(sourceName, new Properties());
    7. } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
    8. Properties propertiesFromYaml = loadYml(resource);
    9. return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    10. } else {
    11. return super.createPropertySource(name, resource);
    12. }
    13. }
    14. private Properties loadYml(EncodedResource resource) throws IOException {
    15. YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    16. factory.setResources(resource.getResource());
    17. factory.afterPropertiesSet();
    18. return factory.getObject();
    19. }
    20. }
    1. @PropertySource(value = {"classpath:config.properties"},encoding="gbk",factory = YmlConfigFactory.class)

    二、Environment读取文件

    配置文件我们继续用上面的两个,定义一个类去读取配置文件

    1. @Configuration
    2. @PropertySource(value = {"classpath:config.properties"},encoding="gbk")
    3. public class GetProperties {
    4. @Autowired
    5. Environment environment;
    6. public String getEnvConfig(){
    7. String name = environment.getProperty("zhbin.config.web-configs.name");
    8. String age = environment.getProperty("zhbin.config.web-configs.age");
    9. return name+"-----"+age;
    10. }
    11. }

    三、@ConfigurationProperties读取配置文件

    @ConfigurationProperties可以将配置文件直接映射成一个实体类,然后我们可以直接操作实体类来获取配置文件相关数据。
    新建一个yml文件,当然properties文件也没问题

    1. zhbin:
    2. config:
    3. web-configs:
    4. name: Java旅途
    5. age: 20

    新建实体类用来映射该配置

    1. @Component
    2. @ConfigurationProperties(prefix = "zhbin.config")
    3. @Data
    4. public class StudentYml {
    5. // webConfigs务必与配置文件相对应,写为驼峰命名方式
    6. private WebConfigs webConfigs = new WebConfigs();
    7. @Data
    8. public static class WebConfigs {
    9. private String name;
    10. private String age;
    11. }
    12. }
  • prefix = “zhbin.config”用来指定配置文件前缀

如果需要获取list集合,则做以下修改即可。

  1. zhbin:
  2. config:
  3. web-configs:
  4. - name: Java旅途
  5. age: 20
  6. - name: Java旅途2
  7. age: 202
  1. @Component
  2. @ConfigurationProperties(prefix = "zhbin.config")
  3. @Data
  4. public class StudentYml {
  5. private List<WebConfigs> webConfigs = new ArrayList<>();
  6. @Data
  7. public static class WebConfigs {
  8. private String name;
  9. private String age;
  10. }
  11. }

通过@ConfigurationProperties读取并校验

我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式:

  1. my-profile:
  2. name: Guide
  3. email: koushuangbwcx@
  4. 复制代码

ProfileProperties 类没有加 @Component 注解。我们在我们要使用ProfileProperties 的地方使用@EnableConfigurationProperties注册我们的配置 bean:

  1. import lombok.Getter;
  2. import lombok.Setter;
  3. import lombok.ToString;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.validation.annotation.Validated;
  7. import javax.validation.constraints.Email;
  8. import javax.validation.constraints.NotEmpty;
  9. /**
  10. * @author shuang.kou
  11. */
  12. @Getter
  13. @Setter
  14. @ToString
  15. @ConfigurationProperties("my-profile")
  16. @Validated
  17. public class ProfileProperties {
  18. @NotEmpty
  19. private String name;
  20. @Email
  21. @NotEmpty
  22. private String email;
  23. //配置文件中没有读取到的话就用默认值
  24. private Boolean handsome = Boolean.TRUE;
  25. }
  26. 复制代码

具体使用:

  1. package cn.javaguide.readconfigproperties;
  2. import org.springframework.beans.factory.InitializingBean;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. /**
  8. * @author shuang.kou
  9. */
  10. @SpringBootApplication
  11. @EnableConfigurationProperties(ProfileProperties.class)
  12. public class ReadConfigPropertiesApplication implements InitializingBean {
  13. private final ProfileProperties profileProperties;
  14. public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
  15. this.profileProperties = profileProperties;
  16. }
  17. public static void main(String[] args) {
  18. SpringApplication.run(ReadConfigPropertiesApplication.class, args);
  19. }
  20. @Override
  21. public void afterPropertiesSet() {
  22. System.out.println(profileProperties.toString());
  23. }
  24. }

因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:

  1. Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed:
  2. Property: my-profile.email
  3. Value: koushuangbwcx@
  4. Origin: class path resource [application.yml]:5:10
  5. Reason: must be a well-formed email address

我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:

  1. ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true)

@PropertySource读取指定 properties 文件

  1. import lombok.Getter;
  2. import lombok.Setter;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. @PropertySource("classpath:website.properties")
  8. @Getter
  9. @Setter
  10. class WebSite {
  11. @Value("${url}")
  12. private String url;
  13. }
  14. 复制代码

使用:

  1. @Autowired
  2. private WebSite webSite;
  3. System.out.println(webSite.getUrl());//https://javaguide.cn/