前期面試的時候被面試官問到,Spring注入某接口,而接口有多實現,應該如何處理。接口多實現很常見,但在業務邏輯開發中,需要考慮注入某接口的多個實現問題的情況並不多見。當時是一臉懵逼,目前有時間,就做出整理如下:
解決這一問題的關鍵在於:@Qualifier注解。需傳入value,值為接口對應實現類的bean_name。搭配@Autowired指向具體實現類在spring容器中的bean。
注意:如果注入的接口有多個實現,而未用@Qualifier去指定具體某一個,編譯期報錯。
關於Qualifier注解:
/** * This annotation may be used on a field or parameter as a qualifier for * candidate beans when autowiring. It may also be used to annotate other * custom annotations that can then in turn be used as qualifiers. * * @author Mark Fisher * @author Juergen Hoeller * @since 2.5 * @see Autowired */ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Qualifier { String value() default ""; }
實際使用代碼如下:
@Qualifier("userServiceImpl")
@Autowired
private UserService userService;
@Qualifier("userServiceTestImpl")
@Autowired
private UserService userServiceTest;
