Home > Enterprise >  @ConditionalOnProperty and "defaultValue": true
@ConditionalOnProperty and "defaultValue": true

Time:03-24

This is off-topic:
Recently, I was refused help and an act of Russophobia was made in my direction.
I am only 16 years old, and I am definitely out of politics. I believe that StackOverflow community is open to everyone, regardless of nationality. Thank you.

Hi! I have a starter with some AOP logic. Please look at my autoconfiguration for it:

@Configuration
@EnableAspectJAutoProxy
@ConditionalOnProperty("simple-security.enabled")
public class AopAutoConfiguration {

    @Bean
    internal fun securedControllerMethodAspect() = SecuredControllerMethodAspect()
}

As you can see, I'm using @ConditionalOnProperty("simple-security.enabled") annotation. Now, look at my additional-spring-configuration-metadata.json:

{
  "properties": [
    {
      "name": "simple-security.enabled",
      "type": "java.lang.Boolean",
      "description": "Whether to enable simple security.",
      "sourceType": "dev.d1s.security.properties.SimpleSecurityConfigurationProperties",
      "defaultValue": true
    }
  ]
}

So, my question is simple: why doesn't Spring take into account the defaultValue value for this property while calculating the condition?

CodePudding user response:

The file additional-spring-configuration-metadata.json doesn't decide how spring will behave, rather it is to give the user a hint how to use your autoconfiguration. And in this case the hint is not accurate to what you have implemented.

If you want Spring to behave the same way when simple-security.enabled is not set and when it set to true you can make use of matchIfMissing param in the annoation @ConditionalOnProperty.

The above can be rewritten as follows:


@ConditionalOnProperty("simple-security.enabled", matchIfMissing = true)

Alternatively, the default value of simple-security.enabled can be set in the class dev.d1s.security.properties.SimpleSecurityConfigurationProperties.

something like this:

/**
 * @property enabled Whether to enable simple security. Enabled by default. 
 */
@ConfigurationProperties(prefix = "simple-security")
data class SimpleSecurityConfigurationProperties(
    var enabled: Boolean = true
)

P/s: I would suggest you let Spring generate the metadata instead of writing it manually. You can refer to this document: https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html#appendix.configuration-metadata.annotation-processor

  • Related