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实例。
  • 相关阅读:
    Ajax请求过程中显示“进度”的简单实现
    Asp.net 图片文件防盗链介绍
    ASP.NET MVC验证
    MVC文件上传
    MVC文件上传-使用jQuery.FileUpload和Backload组件实现文件上传
    使用jQuery.FileUpload插件和服Backload组件自定义上传文件夹
    使用jQuery.FileUpload和Backload自定义控制器上传多个文件
    使用jQuery.FileUpload插件和Backload组件裁剪上传图片
    CSS3 多列
    CSS3 2D转换 动画
  • 原文地址:https://www.cnblogs.com/8593l/p/12928488.html
Copyright © 2011-2022 走看看