📜  具有依赖对象的Spring构造函数注入

📅  最后修改于: 2020-12-04 07:17:54             🧑  作者: Mango

依赖对象的构造方法注入

如果这些类之间存在HAS-A关系,则首先创建依赖对象(包含对象)的实例,然后将其作为主类构造函数的参数传递。在这里,我们的场景是员工HAS-A地址。 Address类对象将称为从属对象。让我们首先看一下Address类:

此类包含三个属性,一个构造函数和toString()方法以返回这些对象的值。

package com.javatpoint;

public class Address {
private String city;
private String state;
private String country;

public Address(String city, String state, String country) {
    super();
    this.city = city;
    this.state = state;
    this.country = country;
}

public String toString(){
    return city+" "+state+" "+country;
}
}

它包含三个属性id,name和address(从属对象),两个构造函数和show()方法,以显示当前对象(包括依赖对象)的记录。

package com.javatpoint;

public class Employee {
private int id;
private String name;
private Address address;//Aggregation

public Employee() {System.out.println("def cons");}

public Employee(int id, String name, Address address) {
    super();
    this.id = id;
    this.name = name;
    this.address = address;
}

void show(){
    System.out.println(id+" "+name);
    System.out.println(address.toString());
}

}

ref属性用于定义另一个对象的引用,以这种方式我们将依赖对象作为构造函数参数传递。




















此类从applicationContext.xml文件获取Bean并调用show方法。

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {
    public static void main(String[] args) {
        
        Resource r=new ClassPathResource("applicationContext.xml");
        BeanFactory factory=new XmlBeanFactory(r);
        
        Employee s=(Employee)factory.getBean("e");
        s.show();
        
    }
}