Spring 我可以从自动配置中排除特定属性吗
我正在使用spring boot并尝试使用“PropertySourcesPlaceholderConfigurer”从文件系统加载外部属性文件, 但我得到了如下错误:Spring 我可以从自动配置中排除特定属性吗,spring,spring-boot,Spring,Spring Boot,我正在使用spring boot并尝试使用“PropertySourcesPlaceholderConfigurer”从文件系统加载外部属性文件, 但我得到了如下错误: Binding to target org.springframework.boot.autoconfigure.web.ServerProperties@3ec11999 failed: Property: server.environment Value: BETA Reason: Failed t
Binding to target org.springframework.boot.autoconfigure.web.ServerProperties@3ec11999 failed:
Property: server.environment
Value: BETA
Reason: Failed to convert property value of type [java.lang.String] to required type [org.springframework.core.env.Environment] for property 'environment'; ...
这是因为spring boot尝试自动配置“ServerProperties”,而“ServerProperties”看起来像:
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {
...
private Environment environment;
...
}
因此,它尝试“解析”任何带有“服务器”前缀的属性
不幸的是,我们的遗留属性文件碰巧包含一个名为
server.environment=BETA
所以SpringBoot尝试将字符串“BETA”转换为“Environment”对象
有没有一种方法可以将“server.environment”从spring boot的自动配置中排除?我认为您不能排除单个属性,但您可以在将
字符串
转换为环境
时,使trick spring boot保留原始环境
对象
@Component
@ConfigurationPropertiesBinding
class OriginalEnvironmentPreservingStringToEnvironmentConverter implements GenericConverter {
private static final Set<ConvertiblePair> CONVERTIBLE_TYPES;
static {
Set<ConvertiblePair> types = new HashSet<>();
types.add(new ConvertiblePair(String.class, Environment.class));
CONVERTIBLE_TYPES = Collections.unmodifiableSet(types);
}
private final Environment environment;
public OriginalEnvironmentPreservingStringToEnvironmentConverter(Environment environment) {
this.environment = environment;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return CONVERTIBLE_TYPES;
}
@Override
public Object convert(final Object o, final TypeDescriptor typeDescriptor, final TypeDescriptor typeDescriptor1) {
return environment;
}
}
@组件
@配置属性绑定
类OriginalEnvironmentPreservingStringToEnvironmentConverter实现GenericConverter{
私有静态最终设置可转换类型;
静止的{
Set types=new HashSet();
添加(新的ConvertiblePair(String.class,Environment.class));
可转换类型=集合。不可修改集(类型);
}
私人最终环境;
公共源环境PreservingString环境转换器(环境){
这个。环境=环境;
}
@凌驾
公共集getConvertibleTypes(){
返回类型;
}
@凌驾
公共对象转换(最终对象o、最终类型描述符TypeDescriptor、最终类型描述符TypeDescriptor 1){
回归环境;
}
}
但我不确定是否会有任何副作用。在简单的场景中,它确实可以很好地工作。可以排除私有环境;或者重新命名这个文件?