-1

我的问题很简单:使用构造函数注入,知道 ClassA 只有一个构造函数(没有 setter 和 getter),我如何才能获得在 ClassB 中声明为属性的类 ClassA 的属性?

在这里,我将编写我的 java 代码:

A类:

public class ClassA {

  public int x1;
  public String x2;

  ClassA(int x1, String x2) {
    this.x1 = x1;
    this.x2 = x2;
  }
}

B类:

public class ClassB {

  private ClassA a;
  private String y1;
  private String y2;

  public ClassA getA() {
    return a;
  }

  public void setA(Class a) {
    this.a = a;
  }

  public String getY1() {
    return y1;
  }

  public void setY1(String y1) {
    this.y1 = y1;
  }

  public String getY2() {
    return y2;
  }

  public void setY2(String y2) {
    this.y2 = y2;
  }
}

主程序:

public class ConstructorInjection {
    public static void main(String args[]){
        Resource xmlResource = new FileSystemResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(xmlResource);
        ClassB b= (ClassB)factory.getBean("bBean");
        ClassA a= b.getA();
        System.out.println("y1="+b.getY1);
        System.out.println("y2="+b.getY2);
        System.out.println("x1="+a.x1);
        System.out.println("x2="+a.x2);
    }
}

这是练习构造函数注入的正确例子吗?

xml配置:

应用程序上下文.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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean id="bBean" class="javabeat.net.spring.ioc.ClassB">
        <property name="y1" value="expy1" />
        <property name="y2" value="expy2" />
        <property name="a" ref="aBean" />
    </bean>

    <bean id="aBean" class="javabeat.net.spring.ioc.ClassA">
        <constructor-arg name="x1" type="java.lang.int" value="0"/>
        <constructor-arg name="x2" type="java.lang.String" value="exp"/>
    </bean>

</beans>

这部分让我感到困扰:

System.out.println("x1="+a.x1);
System.out.println("x2="+a.x2);

不知道这是否是获得ClassA属性的正确方法!我读过构造函数注入强制初始化属性,但是在哪里?在xml配置中?还是在主程序中?

非常感谢你:)

4

2 回答 2

0

关于您对以下问题的关注:

System.out.println("x1="+a.x1); System.out.println("x2="+a.x2);

x1 和 x2 都是私有变量,因此您将无法像以前那样使用 a.x1 或 a.x2。您需要 x1 和 x2 的公共吸气剂。没有看到您的 application.xml,很难再说什么。请给出一些可以运行的代码。

于 2016-05-27T09:52:43.047 回答
0

将 applicationContext.xml 中的 aBean 修改为

<bean id="aBean" class="javabeat.net.spring.ioc.ClassA">
    <constructor-arg name="x1" type="int" value="0"/>
    <constructor-arg name="x2" type="java.lang.String" value="exp"/>
</bean>
于 2016-05-27T10:46:23.777 回答