繁体   English   中英

Spring 构造函数参数和属性未设置值

[英]Spring constructor-arg and property are not setting values

我有一个 DrawingApp 类,它需要在 spring 中使用 spring.xml 配置的 Triangle 对象。 构造函数参数和属性没有设置三角形对象的实例变量。

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApp {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Triangle triangle = (Triangle) context.getBean("triangle");
        System.out.println(triangle);
    }

}
public class Triangle {
    
    private String type;
    private int height;
    public Triangle() {
    }
    public Triangle(String type) {
        this.type = type;
    }
    public Triangle(int height) {
        this.height = height;
    }
    public Triangle(String type, int height) {
        this.type = type;
        this.height = height;
    }
    
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    
    public void draw() {
        System.out.println(getType() + " Triangle drawn of height " + getHeight());
    }
    public String toString() {
        return "Height = " + height + " type = " + type;
    }
}

弹簧文件

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

    <bean id="triangle" class="com.spring.springDemoJavaBrains.Triangle">
        <!-- <property name="type" value="equilateral" /> -->
        <constructor-arg type="java.lang.String" value="equilateral" />
        <constructor-arg type="int" value="20" />
    </bean>
</beans>

这是我在运行 DrawingApp 时收到的输出

高度 = 0 类型 = 空

尝试以下

  <bean id="triangle" class="com.spring.springDemoJavaBrains.Triangle">
     
     <constructor-arg index="0">
          <value>equilateral</value>
     </constructor-arg>

     <constructor-arg index="1">
          <value>20</value>
     </constructor-arg>
    </bean>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM