2 回答
TA贡献1995条经验 获得超2个赞
为此,您可以使用@Configurationclass,您可以在其中创建另一个基于主要和可选 bean 的合格 bean:
@Configuration
class Config {
@Primary @Bean
ObjectMapper primary() {...}
@Bean
ObjectMapper qualified(){...}
@Bean
ObjectMapper resulted(ObjectMapper primary,
@Autowired(required = false) @Qualifier("qualified") ObjectMapper qualified){
return qualified == null ? primary : qualified;
}
}
并将结果 bean 用作:
@Service
class MyService {
MyService(@Qualifier("resulted") ObjectMapper mapper) {...}
}
TA贡献1801条经验 获得超15个赞
尝试这个
@Autowired
private ApplicationContext applicationContext;
@Autowired
private ObjectMapper objectMapper;
然后
try {
ObjectMapper obj = applicationContext.getBean("qualifiedObjectMapper");
//use qualifier
}catch(Exception e) {
//use objectMapper
}
添加回答
举报