English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Nous pouvons également injecter des dépendances par la méthode setter. <bean>de <property>Les éléments sous-element sont utilisés pour l'injection par setter. Ici, nous devons injecter
valeurs originales et basées sur les chaînes de caractères objet dépendant (contient des objets) valeur de collection
Voyons maintenant l'injection des valeurs originales et des valeurs basées sur les chaînes via les méthodes setter. Nous avons créé ici trois fichiers :
Employee.java applicationContext.xml Test.java
Employee.java
C'est une classe simple, contenant trois champs id, name et city, leurs méthodes setteurs et getters, ainsi qu'une méthode pour afficher ces informations.
package com.w3codebox; public class Employee { private int id; private String name; private String city; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } void display(){ System.out.println(id+" "+name+" "+city); } }
applicationContext.xml
Nous fournissons des informations au Bean via ce fichier. L'élément property appelle la méthode setter. L'élément value de l'attribut attribut assigne la valeur spécifiée.
<?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="obj" class="com.w3codebox.Employee"> <property name="id"> <value>20</value> </property> <property name="name"> <value>Arun</value> </property> <property name="city"> <value>ghaziabad</value>/value> </property> </bean> </beans>
Test.java
Cette classe récupère le Bean à partir du fichier applicationContext.xml et appelle la méthode affichage.
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 e = (Employee) factory.getBean("obj"); s.display(); } }
Sortie:
20 Arun ghaziabad