English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
como inyección de constructor, podemos usar inyección de setter para otra dependencia de bean. En este caso, usamos
property
elemento. En este contexto, nuestra escena es
Employee HAS-A Address
。 La clase Address se denominará objeto dependiente. Vamos a ver primero la clase Address:
Address.java
Esta clase contiene cuatro propiedades, es decir, setter y getter y el método toString().
paquete com.w3codebox;
public class Address {
private String addressLine1,city,state,country;
//getters and setters
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
Employee.java
contiene tres propiedades id, nombre y dirección (objeto dependiente), utilizando los métodos setter y getter de displayInfo().
paquete com.w3codebox; public class Employee { private int id; private String name; private Address address; //establecedores y getters void displayInfo(){ System.out.println(id+" "+name); System.out.println(address); } }
applicationContext.xml
propiedad
del elemento
ref Atributo utilizado para definir una referencia a otro bean.
<?xml version="1.0" codificación="UTF-8"?>
<beans
xmlns="http://www.springframework.org/esquema/beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instancia
xmlns:p="http://www.springframework.org/esquema/p
xsi:schemaLocation="http://www.springframework.org/esquema/beans
http://www.springframework.org/esquema/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
Esta clase obtiene el Bean del archivo applicationContext.xml y llama al método displayInfo().
paquete com.w3codebox; 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(); } }