📜  具有依赖对象的Spring Setter注入

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

带有依赖对象的Setter注入示例

像构造函数注入一样,我们可以使用setter注入另一个bean的依赖项。在这种情况下,我们使用property元素。在这里,我们的场景是Employee HAS-A Address 。 Address类对象将称为从属对象。让我们首先看一下Address类:

此类包含四个属性,即setter和getter以及toString()方法。

package com.javatpoint;

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

//getters and setters

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

它包含三个属性id,name和address(从属对象),带有setInfo和getter的displayInfo()方法。

package com.javatpoint;

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

//setters and getters

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

属性元素的ref属性用于定义另一个bean的引用。


















此类从applicationContext.xml文件获取Bean,然后调用displayInfo()方法。

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

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