Search code examples
javaspringspring-boot

Spring: Use @Qualifier()-qualified bean if available, otherwise use any


I'm trying to create a component that will accept a bean (fasterxml ObjectMapper) to be specific.

If there is a qualified bean named qualifiedObjectMapper, I want to use that bean.

If there isn't a bean with that name, but there is an ObjectMapper bean at all, I want to use that.

As far as I know, if I do this:

class MyClass(
  @Qualified("qualifiedObjectMapper") objectMapper: ObjectMapper
)

It will only work if there is a bean with that name, but won't use another ObjectMapper bean if there isn't (if there are multiple, use the primary).

Is there a way to use the qualified if it exists, otherwise use the primary?


Solution

  • For doing this you can use @Configuration class, where you create another qualified bean based on primary and optional ones:

    @Configuration
    class Config {
        @Primary @Bean
        ObjectMapper primary() {...}
    
        @Bean
        ObjectMapper qualified() {...}
    
        @Bean
        ObjectMapper resulted() {
           return qualified() == null ? primary() : qualified();
        }
    }
    

    And use that resulted bean as:

    @Service
    class MyService {
        MyService(@Qualifier("resulted") ObjectMapper mapper) {...}
    }