簡體   English   中英

春季:使用@Qualifier()限定的bean(如果可用),否則使用任何

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

我正在嘗試創建一個組件,該組件將接受特定的bean( fasterxml ObjectMapper )。

如果有一個名為qualifiedObjectMapper的合格bean,我想使用該bean。

如果沒有使用該名稱的bean,但是根本沒有一個ObjectMapper bean,我想使用它。

據我所知,如果我這樣做:

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

僅當存在具有該名稱的bean時,它才起作用,但如果不存在則不使用另一個ObjectMapper bean(如果有多個,則使用主對象)。

有沒有一種方法可以使用合格的(如果存在的話),否則使用主要的?

為此,您可以使用@Configuration類,在該類中,您可以基於主對象和可選對象創建另一個合格的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;
    }
}

並將結果豆用作:

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

嘗試這個

    @Autowired
private ApplicationContext applicationContext;

@Autowired
private ObjectMapper objectMapper;

接着

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM