我可以从自动配置中排除特定属性

时间:2016-10-12 10:27:38

标签: spring spring-boot

我使用spring-boot并尝试使用" PropertySourcesPlaceholderConfigurer"从文件系统加载外部属性文件, 但我收到如下错误:

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
        implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {

    ...
    private Environment environment;
    ...
}

这是因为spring-boot尝试自动配置" ServerProperties"和" ServerProperties"看起来像:

server.environment=BETA

所以它试图解析"任何带有"服务器"前缀。

不幸的是,我们的旧版属性文件恰好包含一个名为

的无关属性
/list?freesearch=value1&limit_content=value2

所以spring-boot尝试转换字符串" BETA"到了环境"对象

有没有办法可以排除" server.environment"从spring-boot的autoconfigure?

1 个答案:

答案 0 :(得分:2)

我认为您不能排除单个属性,但是您可以在将Environment转换为String时使用Spring Boot来保留原始Environment对象。

@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;
    }
}

我不确定是否会有任何副作用。在简单的情况下,它确实可以正常工作。