SpringBoot 版本2.1.4.RELEASE
自定义属性源有两种比较简单的方式:
1、实现EnvironmentPostProcessor接口
2、实现PropertySourceLoader接口
然后在META-INF/spring.factories添加相应配置
1、实现EnvironmentPostProcessor接口
该接口中仅含有一个方法:
void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application)
属性从哪里加载,怎么加载,可以自己实现,几乎没有任何限制,只要经过处理,最后能变成Key:Value形式的都可以,如redis、http、数据库、json,xml等。以Properties类型文件为例,如下所示:
public class HelloEnvironmentPostProcessor implements EnvironmentPostProcessor {
/**
* 属性文件路径
*/
public static final String EXTENSION_FILE_PATH = "C:\\Users\\Administrator\\Desktop\\hello.properties";
/**
* 可以加载任意来源的属性
* @param environment
* @param application
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
try {
Properties properties = new Properties();
properties.load(new FileInputStream(EXTENSION_FILE_PATH));
//环境名称随意取,但尽量不能和其他环境名称相同,避免不生效
PropertiesPropertySource propertySource = new PropertiesPropertySource("environmentPostProcessor", properties);
environment.getPropertySources().addLast(propertySource);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在resources下新建META-INF文件夹,再创建spring.factories(文件名不能修改)文件。
org.springframework.boot.env.EnvironmentPostProcessor=com.wit.sb.studysb.web.config.HelloEnvironmentPostProcessor
其中HelloEnvironmentPostProcessor为实现了EnvironmentPostProcessor接口的全类名。
配置文件内容如下图所示:
2、实现PropertySourceLoader接口
该接口中含有两个方法:
1) String[] getFileExtensions()
2) List<PropertySource<?>> load(String name, Resource resource) throws IOException
该种方法的有些许限制:
1、文件必须放在classpath下
2、文件名必须为application,但文件后缀没有限制
3、getFileExtensions接口返回的文件后缀不能带有.(扩展名不含.)
以上限制是在SpringBoot2.1.4.RELEASE版本下亲测,不知其他版本是否有限制
代码如下所示
public class HelloPropertySourceLoader implements PropertySourceLoader {
/**
* 文件名称只能限制为application
* 文件后缀无限制,
* 且文件只能放在classpath下
* 扩展名不含.
* @return
*/
@Override
public String[] getFileExtensions() {
return new String[]{"abc"};
}
@Override
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
String splitChar = "===";
InputStream is = resource.getInputStream();
List<String> lines = IOUtils.readLines(is);
Properties prop = new Properties();
lines.stream().forEach(line -> {
String[] kv = line.split(splitChar);
prop.setProperty(kv[0], kv[1]);
});
//环境名称随意取,但尽量不能和其他环境名称相同,避免不生效
PropertySource propertySource = new PropertiesPropertySource("propertySourceLoader", prop);
return Arrays.asList(propertySource);
}
}
配置文件如下图所示:
spring.factories配置:
org.springframework.boot.env.PropertySourceLoader=com.wit.sb.studysb.web.config.HelloPropertySourceLoader
该方式限制较多,可能使用比较不方便,不建议使用。
总结:
1、第二种方式在第一种方式前执行
2、第二种方式限制较多,可以优先考虑第一种方式。
3、这两方式加载的时候,日志系统还未完成初始化。由下图可以看出,故只能通过System.out.print打印执行顺序。
github代码