SpringBoot如何启动自动加载自定义模块yml文件(PropertySourceFactory)
作者:君哥聊编程
参考:https://deinum.biz/2018-07-04-PropertySource-with-yaml-files/
背景
自定义模块时经常会编写当前模块的一些核心yml配置,如果要被Spring容器加载到通常的做法是将自定义模块的yml命名为application-模块名.yml,比如db模块命名为application-db.yml,然后再在spring.profiles.include中引入该db,即可加载到子模块配置(前提是maven构建时能够将resources资源目录编译进去)。
上面说的这种限制有很多,子模块对于父模块是黑箱操作,我们无法得知有多少个子模块要被include进来,而且前缀必须以application开头。
今天我们来看另外一种更加灵活的方式,自定义名称的yml直接在子模块中加载,各位朋友继续往下看PropertySourceFactory如何实现。
总结3步走
定义一个YamlPropertySourceFactory,实现PropertySourceFactory,重写createPropertySource方法
将接口给过来的资源流文件使用加载到spring提供的YmlPropertiesFactorBean中,由该工厂Bean产出一个Properties对象
将生成的Properties对象传入PropertiesPropertySource中产出一个PropertySource对象
import lombok.AllArgsConstructor;
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.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @description:
* @author: jianjun.ren
* @date: Created in 2020/9/24 12:05
*/
@AllArgsConstructor
public class YamlPropertySourceFactory implements PropertySourceFactory {
//这个方法有2个入参,分别为资源名称和资源对象,这是第一步
public PropertySource< ? > createPropertySource(String name, EncodedResource resource) throws IOException {
//这是第二步,根据流对象产出Properties对象
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
assert sourceName != null;
//这是第三部,根据Properties对象,产出PropertySource对象,放入到Spring中
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) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
}
创建咱们是说完了,小伙伴有很多问号,怎么去使用呢?
接下来我们再看康康:
在任意一个@Configuration类中,你自己写一个也可以,反正能够被Spring所扫描的
加入下面这段代码,其实就一行:
@Configuration
//这个地方的YamlPropertySourceFactory就是上面编写的代码类
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:xxx-xxx.yml")
public class XXXXConfiguration {
}
最后
好了到这里就结束了,去使用看看效果吧~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
