实现EnvironmentPostProcessor接口的类,可以做到:自定义启动配置项,允许上下文加载前定制化环境变量
- 直接看EnvironmentPostProcessor类代码
package org.springframework.boot.env;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
/**
* 注释翻译后:
* 允许上下文加载前定制化环境变量
* 实现EnvironmentPostProcessor的接口,必须在文件 META-INF/spring.factories中注册。
* 即,若不存在文件夹路径META-INF,则在resource下面创建该文件夹,并增加文件spring.factories。
* 注册时使用类的全路径名作为key
* 如果希望“调用有序”,则可以实现Ordered接口或@Ordered注解
*/
@FunctionalInterface
public interface EnvironmentPostProcessor {
/**
* Post-process the given {@code environment}.
* @param environment the environment to post-process
* @param application the application to which the environment belongs
*/
void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);
}
- 定义一个类,实现EnvironmentPostProcessor接口
package com.example.other;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.util.Properties;
/**
自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
*/
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
//Properties对象
private final Properties properties = new Properties();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//自定义配置文件
String[] profiles = {
"swagger.properties"
// "zzz.yml"
};
//循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
//加载单个配置文件
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
try {
//从输入流中加载一个Properties对象
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
}catch (IOException ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}
- 在resources 下添加META-INF文件夹
META-INF文件夹下加上 spring.factories文件,
spring.factories文件中配置org.springframework.boot.env.EnvironmentPostProcessor
#启用我们的自定义环境处理类
org.springframework.boot.env.EnvironmentPostProcessor=com.example.other.MyEnvironmentPostProcessor