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

Esempio di iniezione di setter e oggetto dipendente

Come nel costruttore注入, possiamo utilizzare l'iniezione di setter per l'intera dipendenza di un altro bean. In questo caso, usiamo proprietà elemento. Nel nostro scenario, è Employee HA-A Address。 L'oggetto della classe Address sarà chiamato oggetto dipendente. Prima di tutto, diamo un'occhiata alla classe Address:

Address.java

Questa classe contiene quattro proprietà, setter e getter e il metodo toString().

package com.w3codebox;
public class Address {
private String addressLine1,city,state,country;
//getter e setter
public String toString(){
    return addressLine1+" "+city+" "+state+" "+country;
{}

Employee.java

Contiene tre proprietà id, nome e indirizzo (oggetto dipendente), utilizzando i setter e getter del metodo displayInfo().

package com.w3codebox;
public class Employee {
private int id;
private String name;
private Address address;
//setter e getter
void displayInfo(){
    System.out.println(id+" "+name);
    System.out.println(address);
{}
{}

applicationContext.xml

proprietàelemento ref Proprietà utilizzata per definire il riferimento a un altro bean.

<?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="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

Questa classe recupera il Bean dal file applicationContext.xml e chiama il metodo displayInfo().

package 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();
{}
{}