公众号:WarmSmile

问题由来

SpringBoot 默认只加载当前启动应用下的yml配置,无法加载在Jar内的自定义yml配置类,所以我们需要手动加载自定义yml配置信息

解决方案

主要通过@PropertySource注解加载自定义yml配置文件,通过实现PropertySourceFactory接口进行yml配置的支持

核心代码

  • 在配置类加上@PropertySource注解

@PropertySource 可以搭配@ConfigurationProperties和@Value一起使用的

@PropertySource(value = {"classpath:config.yml"}, factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(value="xx.interface")
public class TestConfig {
    @Value("${ds.address}")
    public  String address;
}
  • 实现PropertySourceFactory接口支持yml配置(默认的接口实现只支持Properties文件结构
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(encodedResource);
        String sourceName = s != null ? s : encodedResource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
}
  • 重新启动应用即可‘’

总结

通过上面的方式就可以解决,自定义Starter的自定义yml无法加载的问题了

如果有其他更好的方式可以评论告诉我!

往期推荐

【设计模式组合拳】建造者+责任链模式

三分钟理解责任链模式

三分钟理解建造者模式

A bird in the hand is worth two in the bush.
奢求未来不如把握当下。
关注公众号:WarmSmile
一起成长一起进步

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐