美文网首页
Springboot中加载自定义的yml配置文件

Springboot中加载自定义的yml配置文件

作者: 和平菌 | 来源:发表于2020-07-22 10:10 被阅读0次

有一些配置需要单独提出来时,如果是properties文件可以@PropertySource注解直接进行加载,但如果是yml文件就需要进行处理
1、创建你的配置文件,比如config.yml,写入配置项
2、创建配置类,并加载配置文件

@Component
@Data
@Configuration
@PropertySource(value = {"classpath:/config.yml"}, factory = CompositePropertySourceFactory.class)
public class MyConfig {

    @Value("${query.pageSize}")
    public int pageSize;

}

3、自定义CompositePropertySourceFactory来加载yml文件
这里有个属性叫factory,默认的factory是DefaultPropertySourceFactory,默认值加载properties文件
我们只需要继承这个类,对其扩展即可

public class CompositePropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            // return an empty Properties
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYaml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }
    /**
     * load yaml file to properties
     *
     * @param resource
     * @return
     * @throws IOException
     */
    private Properties loadYaml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

相关文章

网友评论

      本文标题:Springboot中加载自定义的yml配置文件

      本文链接:https://www.haomeiwen.com/subject/rlhzkktx.html