将默认bean构造函数设为public不会在spring中实例化

时间:2013-11-12 05:29:56

标签: java spring

我是春天新手。我创建了一个bean类和一个配置文件,如下所示:

的beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employee" class="com.asd.bean.Employee">
        <constructor-arg index="0" type="java.lang.String" value="kuldeep" />
        <constructor-arg index="1" type="java.lang.String" value="1234567" />
    </bean>

</beans>

Employee.java

package com.asd.bean;

public class Employee {

    private String name;
    private String empId;

    public Employee() {
        System.out.println("Employee no-args constructor");
    }

    Employee(String name, String empId)
    {
        System.out.println("Employee 2-args constructor");
    this.name=name;
    this.empId=empId;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the empId
     */
    public String getEmpId() {
        return empId;
    }

    /**
     * @param empId the empId to set
     */
    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public String toString() {
        return "Name : "+name+"\nEID : "+empId; 

    }

}

当我尝试使用ApplicationContext获取bean时,它提供以下异常:

线程中的异常&#34; main&#34; org.springframework.beans.factory.BeanCreationException:创建名称为&#39; employee&#39;的bean时出错在类路径资源[Problem.xml]中定义:指定了2个构造函数参数,但在bean&#39; employee&#39;中找不到匹配的构造函数。 (提示:为简单参数指定索引/类型/名称参数以避免类型歧义)

现在,如果我从默认构造函数中删除公共它,它工作正常,即使在将两个构造函数都公开的情况下也可以正常工作。请解释一下为什么会出现这种情况???

先谢谢。

1 个答案:

答案 0 :(得分:2)

我只验证了这在3.2.4中有效,而且在3.0.0上没有。这里讨论的实现是3.0.0中的ConstructorResolver#autowireConstructor()。此方法用于解析要使用的正确构造函数。在此实现中,我们使用返回的Constructor获取所有bean类“Class#getDeclaredConstructors()实例”

  

返回反映所有内容的Constructor对象数组   由此Class对象表示的类声明的构造函数。   返回的数组中的元素没有排序,也没有排序   特别的顺序。

然后通过调用

对这些数组进行排序
AutowireUtils.sortConstructors(candidates);

哪个

  

对给定的构造函数进行排序,首选公共构造函数和   “贪婪”的,有最多的争论。结果将包含   首先是公共构造函数,然后是参数数量减少   非公共构造函数,参数数量也在减少。

换句话说,no-arg构造函数将首先出现,但因为它没有require参数会立即使autowireConstructor()方法抛出Exception,失败。解决方法是让您的其他构造函数具有较少限制的可见性。

在3.2.4实现中,虽然它仍然对构造函数进行排序,但是如果找到的构造函数的参数列表与参数的数量不匹配,则会跳过它。在这种情况下,它会工作。将跳过no arg构造函数,并匹配,解析和使用2参数构造函数。