cdalxndr
cdalxndr

Reputation: 1541

How to make spring mutually exclusive beans?

Using an interface with two bean implementations. One implementation has a conditional.

I want them to be mutually exclusive, resulting in a single bean implementing interface.

Tried the following that results in missing bean:

interface BaseService {}

@Service
@ConditionalOnProperty(...)
class ConditionalService implements BaseService{}

class FallbackService implements BaseService {}

@Configuration
class MyConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public BaseService fallbackService() {
        return new FallbackService();
    }
}

Rejected github issue and sample repo: https://github.com/spring-projects/spring-boot/issues/24227

Upvotes: 1

Views: 622

Answers (1)

MikaelF
MikaelF

Reputation: 3635

In the linked Github issue, the people from Spring Boot already explained why your initial approach wasn't working, so I won't go into that.

Spring Boot doesn't have a @ConditionOnMissingProperty annotation, but you can emulate one using @ConditonalOnExpression, assuming you have something like @ConditionalOnProperty(name = "myproperty", havingValue = "myvalue")

@Bean
    @ConditionalOnExpression("'${myproperty}' != 'myvalue'")
    BaseService fallbackService() {
        return new FallbackService();
    }

Upvotes: 1

Related Questions