背景
在springboot项目中,有时需要引入除application.yml
之外的配置文件(例如在开发公共组件时)。使用@propertysource
注解可以实现这一需求,但有一些细节点需要注意,在此记录。
代码实现
假设有一份名为extra.yml
的配置文件:
# extra.yml extra: name: 张三 order: 3
对应的配置bean为:
@data @configurationproperties("extra") public class extraproperties { private string name; private integer order; }
在配置类上添加相关注解,将extra.yml
配置文件添加到spring环境中:
@configuration @enableconfigurationproperties(extraproperties.class) @propertysource( // 配置文件路径 value = "classpath:/extra.yml", // 当配置文件不存在时,是忽略还是报错 ignoreresourcenotfound = true, // 配置文件编码 encoding = "utf-8", // 配置文件加载工厂 factory = yamlpropertysourcefactory.class) public class extraconfig { }
由于@propertysource
默认支持的是.properties
格式的配置文件,而我们一般使用的是yaml格式的,因此这里自定义了配置文件加载工厂,支持yaml,并解决ignoreresourcenotfound
不生效的问题:
/** * yaml配置文件加载工厂 */ public class yamlpropertysourcefactory implements propertysourcefactory { @override public propertysource<?> createpropertysource(string name, encodedresource resource) throws ioexception { try { return new yamlpropertysourceloader() .load(resource.getresource().getfilename(), resource.getresource()) .get(0); } catch (illegalstateexception e) { // 如果yaml配置文件不存在,希望能忽略该文件,而不是引发异常导致spring容器启动失败 // 需要往外抛filenotfoundexception,spring捕捉到后会忽略该异常(当 ignoreresourcenotfound = true 时) if (e.getcause() instanceof filenotfoundexception) { throw (filenotfoundexception) e.getcause(); } else { throw e; } } } }
这样,extraproperties配置bean里的属性值, 就与extra.yml里的配置值绑定在一起了。
补充说明
标准配置文件application.yml的生效优先级高于额外引入的配置文件。如果application.yml中指定了相同的配置项,则它会覆盖extra.yml中对应的配置项:
# application.yml,会覆盖extra.yml中的相同配置项 extra: name: 李四 order: 4
当然,如果使用了环境配置文件application-{profile}.yml,则它的生效优先级又会高于application.yml。
另外,@propertysource支持引入多个配置文件。例如,在引入extra.yml的同时,引入对应的环境配置文件extra-{profile}.yml:
@configuration @enableconfigurationproperties(extraproperties.class) @propertysource( value = {"classpath:/extra.yml", "classpath:/extra-${spring.profiles.active}.yml"}, ignoreresourcenotfound = true, encoding = "utf-8", // 配置文件加载工厂 factory = yamlpropertysourcefactory.class) public class extraconfig { }
这里,spring会将占位符${spring.profiles.active}解析为对应的值。例如,在application.yml中指定spring.profiles.active=dev,那么配置文件extra-dev.yml会被引入(如有),它的生效优先级高于extra.yml,但低于application.yml。
# extra-dev.yml,会覆盖extra.yml中的相同配置项 extra: name: 王五 order: 5
总结
- @propertysource用于引入额外的配置文件。
- 通过自定义配置文件加载工厂,可支持yaml文件解析,并支持ignoreresourcenotfound。
- 配置文件生效的优先级顺序为:application-{profile}.yml>application.yml>extra-{profile}.yml>extra.yml。
以上就是springboot引入额外的yaml配置文件的代码实现的详细内容,更多关于springboot引入额外yaml文件的资料请关注代码网其它相关文章!
发表评论