English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
을 사용하여 bean 의 parent 속성을 통해 Bean 간의 상속 관계를 지정할 수 있습니다. 이 경우 부모 Bean의 값이 현재 Bean으로 상속됩니다。
bean을 상속받은 간단한 예제를 보겠습니다。
Employee.java
이 클래스는 세 가지 속성, 세 가지 생성자 및 값을 표시하는 show() 메서드를 포함하고 있습니다。
package com.w3codebox; public class Employee { private int id; private String name; private Address address; public Employee() {} public Employee(int id, String name) { super(); this.id = id; this.name = name; } 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); } }
Address.java
package com.w3codebox; public class Address { private String addressLine1, city, state, country; public Address(String addressLine1, String city, String state, String country) { super(); this.addressLine1 = addressLine1; this.city = city; this.state = state; this.country = country; } public String toString(){ return addressLine1+" ""+city+" ""+state+" ""+country; } }
applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="e1" class="com.w3codebox.Employee"> <constructor-arg value="101">/생성자-arg> <constructor-arg value="Sachin"></생성자-arg> </bean> <bean id="address1" class="com.w3codebox.Address"> <constructor-arg value="21,Lohianagar"></생성자-arg> <constructor-arg value="Ghaziabad"></생성자-arg> <constructor-arg value="UP"></생성자-arg> <constructor-arg value="USA"></생성자-arg> </bean> <bean id="e2" class="com.w3codebox.Employee" parent="e1"> <constructor-arg ref="address1">/생성자-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.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 e1=(Employee)factory.getBean("e2"); e1.show(); } }