1

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

cdalxndr
  • 1,435
  • 1
  • 15
  • 20
  • I gave it a shot, but it would help if you specified what kind of parameters you had in your `@ConditionalOnProperty`. It might also be worth taking a look at [this answer](https://stackoverflow.com/a/56775226/7096763) to a similar question. – MikaelF Nov 21 '20 at 00:56
  • @MikaelF in my test case, `@ConditionalOnProperty` will fail, so the bean should not be created, and fallback should be used. End result was no bean was created. – cdalxndr Nov 21 '20 at 08:58
  • Looking at your repo, there’s no `@ConditionalOnProperty`, as the main implementation is defined with a `@ConditionalOnBean`. The Spring Boot people showed you why this doesn’t work. The `@Conditional...` annotations are meant to be used on autoconfiguration classes. Are you looking for help setting one of those up? – MikaelF Nov 21 '20 at 13:15
  • @MikaelF Yes, please provide an example using auto-configuration – cdalxndr Nov 22 '20 at 12:17

1 Answers1

1

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();
    }
MikaelF
  • 3,518
  • 4
  • 20
  • 33