English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Exemple d'injection setter et d'objet dépendant

comme pour l'injection de dépendance via le constructeur, nous pouvons utiliser l'injection setter pour injecter une autre dépendance de bean. Dans ce cas, nous utilisons property éléments. Dans ce scénario, notre scène est Employee AVOIT-A Address。 L'objet de la classe Address sera appelé objet dépendant. Pour commencer, regardons la classe Address :

Address.java

Cette classe contient quatre propriétés, à savoir setter et getter ainsi que la méthode toString().

package com.w;3codebox;
public class Address {
private String addressLine1,city,state,country;
//getters and setters
public String toString(){
    return addressLine1+" "+city+" "+state+" "+country;
}

Employee.java

Il contient trois propriétés id, nom et adresse (objet dépendant), utilisant les méthodes setter et getter de displayInfo().

package com.w;3codebox;
public class Employee {
private int id;
private String name;
private Address address;
//définisseurs et accesseurs
void displayInfo(){
    System.out.println(id+" "+name);
    System.out.println(address);
}
}

applicationContext.xml

propriétéde l'élément ref La propriété est utilisée pour définir une référence à un autre bean.

<?xml version="1.0" encoding="UTF-8"-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

Cette classe récupère le Bean à partir du fichier applicationContext.xml et appelle la méthode 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();
}
}