samanime
samanime

Reputation: 26547

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?

Upvotes: 4

Views: 3273

Answers (2)

Gnk
Gnk

Reputation: 720

try this

@Autowired
private ApplicationContext applicationContext;

@Autowired
private ObjectMapper objectMapper;

and then

try {
    ObjectMapper obj = applicationContext.getBean("qualifiedObjectMapper");
    //use qualifier
}catch(Exception e) {
    //use objectMapper
}

Upvotes: 1

Max Farsikov
Max Farsikov

Reputation: 2763

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) {...}
}

Upvotes: 9

Related Questions