springboot 读取自定义yml配置文件

1.自定义配置文件

在这里插入图片描述

extrarouter:
  maps: {"3d8d4185-598a-4774-b39a-3b2e2d1a1c03":"470",
        "bf12f201-b573-44ec-93e7-dcc09dbb3b4a":"home",
        "ac23328f-1c9d-4576-9c9b-7974787e117e":"home",
        "6de74799-e26b-4074-9afc-591108e08440":"469",
        }

2.自定义配置文件读取配置

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

/**
 * @Description: 重写读取yml配置(springboot中PropertySource的默认实现是properties类型文件的解析)
 * @Prject: booway_software
 * @Package: com.booway.config
 * @author: wanjun
 */
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory
{

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

3.读取自定义配置文件

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "extrarouter")
@PropertySource(value = "classpath:config/application-softwarehelp.yml", factory = YamlPropertySourceFactory.class)
public class SoftHelpExtraRouterConfig
{

    private Map<String, String> maps;

    public Map<String, String> getMaps()
    {
        return maps;
    }

    public void setMaps(Map<String, String> maps)
    {
        this.maps = maps;
    }
}

4.使用

 	@Autowired
    private SoftHelpExtraRouterConfig softHelpExtraRouterConfig;
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值