目录
spring项目开发过程中,配置参数会越来越多,如果都存放在同一个配置文件中,显然使用起来不方便,因此本文说的就是一种拆分的配置文件的方式。
加载默认配置文件
这里是使用environment类自动加载配置文件中的参数。
只要在类中初始化以下变量就行了
@Autowired
private Environment env;
这样就可以自动加载resources下的application文件,后缀可以是yaml、yml、xml。
使用起来也很简单,假设配置文件内容如下
Key1:
Key2:
Key3: 111
获取参数方式如下:
env.getProperty(Key1.Key2.Key3);
批量加载配置文件
文件拆分
拆分前文件层级
resources
|____application.yaml
拆分后文件层级
resources
|____application.yaml
|____client-application1.yaml
|____client-application2.yaml
|____client-application3.yaml
重写environment加载类
新建文件src/main/java/global/env/ClientEnvironmentPostProcessor.java
@Slf4j
public class ClientEnvironmentPostProcessor implements EnvironmentPostProcessor {
private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private final List<PropertySourceLoader> propertySourceLoaders;
public ClientEnvironmentPostProcessor() {
super();
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
for (PropertySourceLoader loader: this.propertySourceLoaders) {
for (String fileExtension: loader.getFileExtensions()) {
String location = ResourceUtiles.CLASSPATH_URL_PREFIX + "/client-*." + fileExtension;
try {
Resource[] resources = this.resourcePatternResolver.getResources(location);
for (Resource resource: resources) {
List<PropertySource<?>> propertySources = loader.load(resource.getFilename(), resource);
if (null != propertySources && !=propertySources.isEmpty()) {
propertySources.stream().forEach(environment.getPropertySources()::addLast);
}
}
} catch (IOException e) {
log.error("加载配置文件失败,因为{}", e.getMessage(), e);
}
}
}
}
}
使能重写的类
resources下新建文件夹META-INF,在META-INF下新建spring.factories文件
org.springframework.boot.env.EnvironmentPostProcessor = \
global.env.ClientEnvironmentPostProcessor