zoukankan      html  css  js  c++  java
  • Spring第九篇:primary指定bean为首选对象

      创建class文件

    public class NoUniqueBean {
        public interface IService{}
        public static class ServiceA implements IService{}
        public static class ServiceB implements IService{}
    
        private IService service;
    
        public void setService(IService service) {
            this.service = service;
        }
    
        @Override
        public String toString() {
            return "NoUniqueBean{" +
                    "service=" + service +
                    '}';
        }
    }

      配置bean.xml文件信息,注意noUniqueBean的自动注入类型是byType。

    <bean id = "serviceB" class="com.java.spring01.demo6.NoUniqueBean.ServiceB" >
        </bean>
        <bean id = "serviceA" class="com.java.spring01.demo6.NoUniqueBean.ServiceA" >
        </bean>
        <bean id = "noUniqueBean" class="com.java.spring01.demo6.NoUniqueBean" autowire="byType"/>

      运行test方法,发现Spring容器在创建bean对象的时候会发现noUniqueBean的IService拥有两个实现类,会抛出异常。

    org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.java.spring01.demo6.NoUniqueBean$IService' available: expected single matching bean but found 2: serviceB,serviceA

      当Spring容器中创建bean对象时,对他注入依赖的属性,发现有多个满足条件的依赖时,会报错。这时可以使用primary指定以哪个依赖为主。就不会出现报错。修改beam.xml文件指定主要的依赖bean对象。

    <bean id = "serviceB" class="com.java.spring01.demo6.NoUniqueBean.ServiceB" primary="true">
        </bean>
        <bean id = "serviceA" class="com.java.spring01.demo6.NoUniqueBean.ServiceA" >
        </bean>
        <bean id = "noUniqueBean" class="com.java.spring01.demo6.NoUniqueBean" autowire="byType"/>

      test方法运行结果

    NoUniqueBean{service=com.java.spring01.demo6.NoUniqueBean$ServiceB@2f0a87b3}

      

      当从容器中查找一个bean的时候,如果容器中出现多个Bean候选者时,可以通过primary="true"将当前bean置为首选者,那么查找的时候就会返回主要的候选者,否则将抛出异常。

      后记:

      在bean标签中加上 autowire-candidate="false",也可以实现,primary的效果,不过autowire-candidate="false"的意思是不做依赖注入的bean实例。
  • 相关阅读:
    CSS印象不深的小地方
    gulp常用插件的使用
    移动端手势库Hammer.js—增强touch事件或手势
    HTML5拖放与文件操作api,实现拖拽上传文件功能
    Less相关
    gulp使用(一)
    将博客搬至CSDN
    jquery Ajax 通过jsonp的方式跨域提交表单
    解决“The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path”问题
    使用eclipse4.5创建maven项目
  • 原文地址:https://www.cnblogs.com/8593l/p/12928488.html
Copyright © 2011-2022 走看看