Ortomala Lokni
Ortomala Lokni

Reputation: 62733

How to load a bean only if a property is false or not defined?

I've a bean that should be loaded only if a property is false or not defined. If I annotate it with:

@ConditionalOnProperty(prefix = "myFeature1", name = "enable", havingValue = "false")

the property myFeature1.enable has to be explicitly set to false. This property is defined as a boolean with a false default value in a @ConfigurationProperties annotated class, but this annotation seems to be treated too late in the application startup so the myFeature1.enable property has to be used as a string from the Environment.

I try to add the annotation:

@ConditionalOnProperty(prefix = "dlcm.module.auth", name = "enable", matchIfMissing = true)

but @ConditionalOnProperty is not a repeatable annotation.

I've also tried to use a @ConditionalOnExpression

@ConditionalOnExpression("'${dlcm.module.auth.enable}' == 'false' or '${dlcm.module.auth.enable}' == ''")

but the property placeholder seems to be replaced by something else than the empty string.

So my question is: How to load a bean only if a property is false or not defined?

Upvotes: 3

Views: 6743

Answers (1)

Ortomala Lokni
Ortomala Lokni

Reputation: 62733

The solution is to use a @ConditionalOnExpression annotation with a default value in the property placeholder:

@ConditionalOnExpression("'${dlcm.module.auth.enable:false}' == 'false'")

Upvotes: 9

Related Questions