English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
의존 객체를 주입하는 것과 마찬가지로, setter 주입을 사용하여 다른 bean의 의존 객체를 주입할 수 있습니다. 이 경우에는
property
요소입니다. 여기서 우리의 상황은
Employee HAS-A Address
Address 클래스 객체는 부속 객체로 불릴 것입니다. 먼저 Address 클래스를 살펴보겠습니다:
Address.java
이 클래스는 네 가지 속성을 포함하고 있으며, setter와 getter 및 toString() 메서드를 포함합니다.
package com.w;3codebox;
public class Address {
private String addressLine;1,city,state,country;
//getters and setters
public String toString(){
return addressLine;1+" "+city+" "+state+" "+country;
}
Employee.java
이 클래스는 세 가지 속성을 포함하고 있습니다. id, 이름, 주소(의존 객체), displayInfo() 메서드의 setter와 getter를 사용합니다.
package com.w;3codebox; public class Employee { private int id; private String name; private Address address; //setter와 getter}} void displayInfo(){ System.out.println(id+" "+name); System.out.println(address); } }
applicationContext.xml
속성
요소의
ref 속성은 다른 bean의 참조를 정의하는 데 사용됩니다.
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="address1" class="com.w3codebox.Address">
<property name="addressLine1" value="51,Lohianagar"></property>
<property name="city" value="Ghaziabad"></property>
<property name="state" value="UP"></property>
<property name="country" value="India"></property>
</bean>
<bean id="obj" class="com.w3codebox.Employee">
<property name="id" value="1></property>
<property name="name" value="Sachin Yadav"></property>
<property name="address" ref="address1></property>
</bean>
</beans>
Test.java
이 클래스는 applicationContext.xml 파일에서 Bean을 가져와 displayInfo() 메서드를 호출합니다.
package com.w;3codebox; 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(); } }