d1snin
d1snin

Reputation: 200

@ConditionalOnProperty and "defaultValue": true

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?

Upvotes: 1

Views: 2297

Answers (1)

Huu Phuong Vu
Huu Phuong Vu

Reputation: 1074

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

Upvotes: 2

Related Questions