springboot 读取自定义yml配置文件

1.自定义配置文件

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;

你可能感兴趣的:(springboot)