English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
依存関係をコンストラクタ注入で注入できます。 <bean>の <constructor-arg>コンストラクタ注入に使用される子要素。ここでは、注入する
原始値と文字列に基づく値 従属オブジェクト(オブジェクトを含む) セット値など
原始値と文字列に基づくシンプルな例を確認してみましょう。ここでは、3つのファイルを作成しました:
Employee.java applicationContext.xml Test.java
Employee.java
これはシンプルなクラスで、idとnameという2つのフィールドを含んでいます。このクラスには4つのコンストラクタと1つのメソッドがあります。
package com.w;3codebox; public class Employee { private int id; private String name; public Employee() {System.out.println("def cons");} public Employee(int id) {this.id = id;} public Employee(String name) { this.name = name;} public Employee(int id, String name) { this.id = id; this.name = name; } void show(){ System.out.println(id+" "+name); } }
applicationContext.xml
このファイルを通じて情報をBeanに提供します。 constructor-arg要素はコンストラクタを呼び出します。この場合、int型のパラメータ化コンストラクタが呼び出されます。Constructor-arg要素のvalue属性は指定された値を割り当てます。type属性はintパラメータのコンストラクタを呼び出すことを指定します。
<?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="e" class="com.w3codebox.Employee"> <constructor-arg value="10" type="int"></constructor-arg> </bean> </beans>
Test.java
このクラスはapplicationContext.xmlファイルからBeanを取得し、showメソッドを呼び出します。
package com.w;3codebox; 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(); } }
出力: 10空
コンストラクタのarg要素にtype属性を指定しない場合、デフォルトで文字列タイプのコンストラクタが呼び出されます。
.... <bean id="e" class="com.w3codebox.Employee"> <constructor-arg value="10></constructor-arg> </bean> ....
bean要素を上記のように変更すると、文字列パラメータのコンストラクタが呼び出され、出力は0になります 10。
出力: 0 10
以下のように文字列文字列を渡すこともできます
.... <bean id="e" class="com.w3codebox.Employee"> <constructor-arg value="Sonoo"></constructor-arg> </bean> ....
出力: 0 Sonoo
整数文字と文字列を以下のように渡すことができます
.... <bean id="e" class="com.w3codebox.Employee"> <constructor-arg value="10" type="int""></constructor-arg> <constructor-arg value="Sonoo"></constructor-arg> </bean> ....
出力: 10 Sonoo