你指的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
---
我认为在YamlPropertyLoaderFactory 中获取活动的个人资料名称并不容易,尽管您可以尝试类似...
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 文件中有活动配置文件名称时,您可以使用 null 调用 YamlPropertySourceLoader().load 以获取 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);
}
}