这个
YamlPropertyLoaderFactory
您所指的具有以下代码:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
}
}
第三个参数
YamlPropertySourceLoader.load()
方法实际上是要为其设置属性的配置文件名称。当这个示例传入null时,它只返回yml文件中的属性集,而不是特定概要文件的属性集。
即
spring:
profiles:
active: p1
---
我不认为这是很容易拿起的活动配置文件名称在
YamlPropertyLoader工厂
,尽管你可以尝试像。。。
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
String activeProfile = System.getProperty("spring.profiles.active");
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), activeProfile);
}
}
或者,当您在yml文件中有活动的概要文件名时,您可以调用
YamlPropertySourceLoader().load
使用null获取spring.profiles.active属性,然后再次调用它以加载所需yml文件的实际部分。
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
PropertySource<?> source = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
String activeProfile = source.getProperty("spring.profiles.active");
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), activeProfile);
}
}
YamlPropertySourceLoader
是在2018年2月更改的(
YamlPropertySourceLoader blame view in Git repo
). 它现在返回propertySource的列表,并且在load方法上没有第三个参数。
如果您在yml文件中有spring.profiles.active属性,那么您就可以在更新版本的
YamlPropertySourceLoader公司
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
for (PropertySource<?> checkSource : sources) {
if (checkSource.containsProperty("spring.profiles.active")) {
String activeProfile = (String) checkSource.getProperty("spring.profiles.active");
for (PropertySource<?> source : sources) {
if (activeProfile.trim().equals(source.getProperty("spring.profiles"))) {
return source;
}
}
}
}
return sources.get(0);
}
}