Search code examples
spring-bootconsulspring-cloud-consul

Consul configuration on conditional property spring boot


How can I write consul configuration class on the conditional property, I have done and tested with properties,

But want to write configuration class and that configuration should be load on condition.


Solution

  • If I got your question right, you want to create a configuration class but load this configuration only if some condition is met:

    @Configuration
    public class MyConfiguration {
          @Bean 
          public ??? myBean() {
             ....
          }
    }
    

    In this case, you should use @Conditional annotation that has been firstly shipped with Spring 4.

    There are many @Conditional-like annotations, you should just peek the one you need.

    • @ConditionalOnClass
    • @ConditionalOnProperty
    • @ConditionalOnMissingProperty
    • @ConditionalOnWebApplication
    • @ConditionalOnBean
    • @ConditionalOnMissingBean
    • @ConditionalOnClass
    • .... (there are others probably)

    If it's not enough you can even roll your own Conditional logic. Since it wasn't asked directly in the question, I'll just provide a link (one among many) articles that shows how to do it.

    So you can go with, for example:

    @Configuration
    @ConditionalOnProperty(value="my.consul.integration.enabled", havingValue = "true")
    public class MyConfiguration {
          @Bean 
          public ??? myBean() {
             ....
          }
    } 
    

    You can also put the conditional logic at the granularity of a single bean.

    Here the requirement is running the consul configuration only if a certain property is enabled (tools.consul.enabled=true from your comments)

    The idea is to define a set of consul related properties not in a default application.yml file but somewhere else, for example consul-integration.properties file, and read this file with configuration that is turned on only if a @ConditionOnProperty is met.

    Example:

    @Configuration
    @ConditionalOnProperty(value="tools.consul.enabled", havingValue=true) 
    @PropertySources({
     @PropertySource("classpath:consul-integration.properties) 
    })
    public class ToolConsulSampleConfiguration {
    
    }