Search code examples
springspring-bootspring-annotationsspring-bean

Spring Boot 2.x.x - Combine 2 conditions in @ConditionalOnProperty


I have the following interface :

@Primary
@ConditionalOnProperty(value = "ms.couchbase.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(value = "iiams.switch.iiamsSingleProcessIdPer100", havingValue = "true", matchIfMissing = true)
public interface AsyncCommonRepository extends CouchbaseRepository<CouchbaseDocument, Long> { }

Of course this does not compile.
All I want is to combine somehow the two @ConditionalOnProperty. Should I use @ConditionalOnExpression?
Thanks in advance!


Solution

  • You can use AllNestedConditions to combine two or more conditions:

    class AsyncCommonRepositoryCondition extends AllNestedConditions {
    
        AsyncCommonRepositoryCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }
    
        @ConditionalOnProperty(value = "ms.couchbase.enabled", havingValue = "true", matchIfMissing = true)
        static class CouchbaseEnabled {
    
        }
    
        @ConditionalOnProperty(value = "iiams.switch.iiamsSingleProcessIdPer100", havingValue = "true", matchIfMissing = true)
        static class SingleProcessIdPer100 {
    
        }
    
    }
    

    This condition can then be used on your repository:

    @Primary
    @Conditional(AsyncCommonRepositoryCondition.class)
    public interface AsyncCommonRepository extends CouchbaseRepository<CouchbaseDocument, Long> { }