关于java:springbootroute二读取配置文件的几种方式

3次阅读

共计 4155 个字符,预计需要花费 11 分钟才能阅读完成。

Spring Boot 提供了两种格局的配置文件,别离是propertiesyml。Spring Boot 最大的特点就是自动化配置,如果咱们想批改自动化配置的默认值,就能够通过配置文件来指定本人服务器相干的参数。

配置文件粗放治理了配置信息,如果把配置参数写到 Java 代码中,保护起来十分不不便,如果应用配置文件,咱们能够对立治理,对立批改。我比拟举荐应用 yml 格局的配置文件,YAML是专门用来写配置文件的语言,通常以 yml 为后缀,它的构造十分清晰,更易于浏览。

将自定义的配置写在配置文件中后,如果想要在 java 代码中应用配置,这时候就须要读取配置文件,读取配置文件的形式有三种,咱们挨个介绍一下如果进行读取!

第一种:应用 @Value 注解读取

第一步:在配置文件中减少退出以下配置

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 文件中新建对象类型的配置信息

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

此是 spring-boot-route 系列的第二篇文章,这个系列的文章都比较简单,次要目标就是为了帮忙首次接触 Spring Boot 的同学有一个零碎的意识。本文已收录至我的 github,欢送各位小伙伴star

github:https://github.com/binzh303/s…

点关注、不迷路

如果感觉文章不错,欢送 关注 点赞 珍藏,你们的反对是我创作的能源,感激大家。

如果文章写的有问题,请不要悭吝,欢送留言指出,我会及时核查批改。

如果你还想更加深刻的理解我,能够微信搜寻「Java 旅途」进行关注。回复「1024」即可取得学习视频及精美电子书。每天 7:30 准时推送技术文章,让你的下班路不在孤单,而且每月还有送书流动,助你晋升硬实力!

正文完
 0