java - Spring以什么顺序获取构造函数参数中的值

标签 java spring

<分区>

我尝试了 DI 的构造函数注入(inject)。即使我没有指定 type,这段代码也能正常工作在 <constructor-arg> .

三角形类:

public class Triangle {

    private String type;
    private int height;

    public Triangle(int height) {
        this.height = height;
    }

    public Triangle(String type, int height) {
        this.type = type;
        this.height = height;
    }

    public Triangle(String type) {
        this.type = type;
    }

    public void draw(){
        System.out.println(getType()+ " Triangle drawn with height = "+getHeight());
    }

    public String getType() {
        return type;
    }

    public int getHeight() {
        return height;
    }
}

配置文件,spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id = "triangle" class = "model.Triangle">
        <constructor-arg value = "Isosceles"/> 
        <constructor-arg value = "20" />
    </bean>
</beans>

驱动类(main 方法):

public class Driver {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Triangle triangle = (Triangle) context.getBean("triangle");
        triangle.draw();
    }
}

但是,当我尝试 <constructor-arg> 的行时在 spring.xml 中可互换,抛出如下异常:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

我无法弄清楚 Spring<constructor-arg> 中获取值的顺序。 .

最佳答案

一个简短的回答:它接受参数的顺序与类构造函数中描述的顺序相同。

来自 Spring docs 的证明(p.7.4.1):

Constructor argument resolution matching occurs using the argument’s type. If no potential ambiguity exists in the constructor arguments of a bean definition, then the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor when the bean is being instantiated.

关于java - Spring以什么顺序获取构造函数参数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093141/

相关文章:

java - Controller 类未加载 Spring

java - 使用 Spring、Scala 和 Jackson 将 JSON 反序列化为 Map[String, SomeJavaObject]

java - 编写Android项目时的常见错误

java - 未报告的异常 java.io.ioexception 必须被捕获或声明为抛出

java - 找到 2 个 java.sql.Timestamps 之间的小时或分钟差异?

java - 如何以编程方式从 spring security 中的 <HTTP> 元素访问 <INTERCEPT-URL>

java - 为什么在屏障操作执行后无法立即获取 cyclingBarrier?

java - 如果您使用基于界面的设计方法,您如何命名更多行为界面?

java - 即使使用 create-session ="stateless",Spring Security Oauth2 也会生成 jsessiond

spring - 使用 Spring Batch 或 Quartz 调度程序来调度作业