zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    「APIO2017」商旅
    【CQOI2017】小Q的表格
    【HNOI2016】树
    【NOI2018模拟】Yja
    测试
    Loj #6073.「2017 山东一轮集训 Day5」距离
    「AHOI / HNOI2017」影魔
    Loj 6068. 「2017 山东一轮集训 Day4」棋盘
    【SDOI2014】向量集
    远程服务器安装nginx
  • 原文地址:https://www.cnblogs.com/nyatom/p/9070733.html
Copyright © 2011-2022 走看看