English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
계층 관계가 있는 경우-A 관계가 있으면, 먼저 종속 객체(포함 객체)의 인스턴스를 생성한 다음 이를 주 클래스 생성자의 매개변수로 전달합니다. 여기서 우리의 시나리오는 직원HAS입니다-A 주소. Address 클래스 객체는 부속 객체로 불릴 것입니다. 우선 Address 클래스를 보도록 하겠습니다:
Address.java
이 클래스는 세 가지 속성, 하나의 생성자 및 toString() 메서드를 포함하여 이러한 객체의 값을 반환합니다.
package com.w3codebox; 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+" "+주+" "+국가; } }
Employee.java
그것은 id, 이름, 주소(부속 객체)의 세 가지 속성, 두 개의 생성자 및 show() 메서드를 포함하여 현재 객체(의존 객체를 포함)의 기록을 표시합니다.
package com.w3codebox; public class Employee { private int id; private String name; private Address address;//조합 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()); } }
applicationContext.xml
ref 속성은 다른 객체의 참조를 정의하는 데 사용됩니다. 예를 들어, 우리는 생성자 매개변수로 의존 객체를 전달합니다.
<?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="a1" class="com.w3codebox.Address"> <constructor-arg value="ghaziabad"></constructor-arg> <constructor-arg value="UP"></constructor-arg> <constructor-arg value="India"></constructor-arg> </bean> <bean id="e" class="com.w3codebox.Employee"> <constructor-arg value="12" type="int"></constructor-arg> <constructor-arg value="Sonoo"></constructor-arg> <constructor-arg> <ref bean="a1"/> </constructor-arg> </bean> </beans>
Test.java
이 클래스는 applicationContext.xml 파일에서 Bean을 가져와 show 메서드를 호출합니다.
package com.w3codebox; 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(); } }