Spring IOC注入接口多实现解决

  前期面试的时候被面试官问到,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;

猜你喜欢

转载自www.cnblogs.com/nyatom/p/9070733.html