Reputation: 26547
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
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
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