使默认的 Bean 构造函数公开不会在 Spring 中实例化



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

豆类.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>

员工.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; 
    }
}

当我尝试使用应用程序上下文获取 bean 时,它给出了以下异常:

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

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

提前谢谢。

我只验证了这在 3.2.4 中有效,而在 3.0.0 上不起作用。这里讨论的实现在 3.0.0 中ConstructorResolver#autowireConstructor()。此方法用于解析要使用的正确构造函数。在此实现中,Constructor我们使用返回 Class#getDeclaredConstructors()

返回一个构造函数对象的数组,这些对象反映了所有 由 Class 对象表示的类声明的构造函数。 返回的数组中的元素未排序,并且不在任何 特定顺序。

然后,它通过调用对这些数组进行排序

AutowireUtils.sortConstructors(candidates);

对给定的构造函数进行排序,首选公共构造函数和 "贪婪"的人,论据最多。结果将包含 首先是公共构造函数,参数数量减少,然后 非公共构造函数,参数数量再次减少。

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

在 3.2.4 实现中,尽管它仍然对构造函数进行排序,但如果发现构造函数的参数列表与参数数不匹配,则会跳过该构造函数。在这种情况下,它将起作用。将跳过 no arg 构造函数,匹配、解析和使用 2 参数构造函数。

最新更新