Search code examples
springcouchbasespring-data-couchbasecouchbase-java-api

Couchbase Template Config Class


I have a Config class for Couchbase as follows:

@Configuration
@EnableCouchbaseRepositories
public class CouchbaseConfig extends AbstractCouchbaseConfiguration{

@Value("${couchbase.serverList:127.0.0.1}")
String IPS;
@Value("${couchbase.disabled}")
boolean disabled;

private static final Logger logger = LogManager.getLogger(CouchbaseConfig.class);
@Override
protected List<String> bootstrapHosts() {
    logger.info("Array List for Couch: " + IPS);
    return Arrays.asList(IPS.split(","));

}

To make it More Team Friendly i want to add a parameter disabled which allows the Application to still run if one member has not got couchbase on his local.

Is it possible?

Something like this is present in Normal couchbase configuration.

@PostConstruct
public void init() {
    if (disabled)
        return;

    logger.info("Opening couchbase connection.");
    try {
        cluster = CouchbaseCluster.create(Arrays.asList(hosts.split(",")));

Solution

  • You can use a nifty little set of annotations from the @Conditional family in Spring 4. This allows you to have Spring consider the annotated method only if the condition described by the annotation is met.

    @Conditional can be put on a method declaring a @Bean, or even on a whole @Configuration class. In the later case, all the beans in the configuration as well as component scan annotations will be subject to the condition.

    Do you use Spring Boot?

    If yes, then good news! There is a lot of @Conditional flavors packaged with Spring Boot. One in particular will suit your needs I think: @ConditionalOnProperty.

    Don't use Spring Boot?

    (give it a try :p)

    The @Conditional annotation is in Spring's core but you have to provide it with a Condition implementation class, so it is up to you to code the Condition (not too complicated an interface, but still).

    Spring Older than 4.x?

    There is also the older alternative of the @Profile annotation from Spring 3.1, where you would classify your configuration into profiles and activate one particular profile at runtime, but it is less flexible...