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

依存オブジェクトのコンストラクタ注入

クラス間にHAS関係がある場合-A関係が存在する場合、まず依存オブジェクト(含むオブジェクト)のインスタンスを作成し、それをメインクラスのコンストラクタの引数として渡します。ここでのシナリオは従業員HASです-A住所。 Addressクラスのオブジェクトは従属オブジェクトと呼ばれます。まず、Addressクラスを見てみましょう:

Address.java

このクラスには、3つの属性、1つのコンストラクタ、およびこれらのオブジェクトの値を返すtoString()メソッドが含まれています。

package com.w3codebox;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
    super();
    this.city = city;
    this.state = state;
    this.country = country;
}
public String toString(){}
    return city+" "+州+" "+國家;
}
}

Employee.java

它包含三個屬性id,名稱和地址(從屬對象),兩個構造函數和show()方法來顯示當前對象(包括依賴對象)的記錄。

package com.w3codebox;
public class Employee {
private int id;
private String name;
private Address address;//集合
public Employee() {System.out.println("def cons");}
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.toString());
}
}

applicationContext.xml

ref 属性用於定義另一個對象的引用,例如,我們將依賴對象傳遞為構造函數參數。

<?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="a1" class="com.w3codebox.Address">
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
<bean id="e" class="com.w3codebox.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>
</beans>

Test.java

このクラスは applicationContex.xml ファイルから Bean を取得し show メソッドを呼び出します。

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 s = (Employee)factory.getBean("e");
        s.show();
        
    }
}