如何仅在特定条件下验证配置属性?

问题描述 投票:0回答:1

我有以下配置属性类:

@Getter
@Setter
@ConfigurationProperties(prefix = "myprops")
public class MyProps {

    private boolean enabled = true;
    @NotEmpty
    private String hostname;
    @NotNull
    private Integer port;

}

我希望仅在

hostname
时才考虑
port
enabled = true
上的验证注释。当
enabled = false
时,不应执行验证。

我已经尝试将验证放入名为

OnEnabled
的验证组中,并尝试在用
@Validated(OnEnabled.class)
注释的
@Configuration
类中应用
@ConditionalOnProperty
,但这似乎不起作用:

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "myprops.enabled", matchIfMissing = true)
public class MyPropsConfiguration {

    @Bean
    @Validated(OnEnabled.class)
    @ConfigurationProperties(prefix = "myprops")
    public MyProps myProps() {
        return new MyProps();
    }

}

我也尝试了以下方法,但它给了我一个关于重复配置属性前缀的编译时错误:

@Configuration(proxyBeanMethods = false)
public class MyPropsAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnProperty(name = "myprops.enabled", matchIfMissing = true)
    public static class MyPropsEnabledConfiguration {

        @Bean
        @Validated
        @ConfigurationProperties(prefix = "myprops")
        public MyProps myProps() {
            return new MyProps();
        }

    }

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnProperty(name = "myprops.enabled", havingValue = "false")
    public static class MyPropsDisabledConfiguration {

        @Bean
        @ConfigurationProperties(prefix = "myprops")
        public MyProps myProps() {
            return new MyProps();
        }
    }

}

将 @ConfigurationProperties 移动到属性类消除了编译错误,但也没有按预期工作

有什么办法可以实现这一点吗?我知道自定义验证器可能是一个解决方案,但我很感兴趣这是否可以通过纯 spring 注释实现?

spring spring-boot configurationproperties
1个回答
0
投票

这对我有用:

@Getter
@Setter
@Validated
@ConfigurationProperties(prefix = "myprops")
public class MyProps {

    private boolean enabled = true;
    @NotEmpty
    private String hostname;
    @NotNull
    private Integer port;
}

配置类应使用EnableConfigurationProperties。然后你应该放置 ConditionalOnProperty 并注入属性。

@Getter
@Setter
@Configuration
@ConditionalOnProperty(prefix = "myprops", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(MyProps.class)
public class MyPropsConfiguration {

    private MyProps myProps;

    // your code...
}
© www.soinside.com 2019 - 2024. All rights reserved.