How to validate configuration properties only on certain condition?

789 Views Asked by At

I have the following configuration properties class:

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

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

}

I want the validation annotations on hostname and port only to be considered when enabled = true. When enabled = false the validation should not be executed.

I have already tried putting the validations inside a validation group named OnEnabled and I tried applying @Validated(OnEnabled.class) in a @Configuration class annotated with @ConditionalOnProperty, but that didn't seem to work:

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

}

I also tried the following, but it is giving me a compile time error about duplicate configuration property prefixes:

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

}

Moving the @ConfigurationProperties to the properties class got rid of the compile error, but also didn't work as expected

Is there any way to achieve this? I know that a custom Validator might be a solution, but I would be interested if this is possible with pure spring annotations?

1

There are 1 best solutions below

0
On

This worked for me:

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

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

Configuration class should use EnableConfigurationProperties. Then you should put ConditionalOnProperty and just inject properties.

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

    private MyProps myProps;

    // your code...
}