English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
依存関係をsetterメソッドで注入することもできます。 <bean>の <property>子要素はSetter注入用です。ここでは、注入する
元のおよび文字列ベースの値 従属オブジェクト(オブジェクトを含む) 集合値など
原始値とsetterメソッドを基にした文字列の値の注入を見てみましょう。ここでは3つのファイルを作成しました:
Employee.java applicationContext.xml Test.java
Employee.java
これは単純なクラスで、id、name、cityという3つのフィールドとそれらのsetterおよびgetter、情報を表示するメソッドを含んでいます。
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
このファイルを通じて、Beanに情報を提供します。property要素はsetterメソッドを呼び出します。属性的value子要素は指定された値を割り当てます。
<?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>アルン</value> </property> <property name="city"> <value>ghaziabad</value>/value> </property> </bean> </beans>
Test.java
このクラスは applicationContex.xml ファイルから Bean を取得し、表示メソッドを呼び出します。
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(); } }
出力:
20 Arun ghaziabad