SpringのBeanプロパティにvalueを挿入する方法
Springでは、Beanプロパティに値を挿入する3つの方法があります。
名前と型の2つのプロパティを含むシンプルなJavaクラスを参照してください。
後でSpringを使用してBeanのプロパティに値を注入します。
package com.mkyong.common;
public class FileNameGenerator
{
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
1.通常の方法
‘value’タグ内の値を注入し、 ‘property’タグで囲みます。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
<property name="name">
<value>mkyong</value>
</property>
<property name="type">
<value>txt</value>
</property>
</bean>
</beans>
2.ショートカット
「値」属性を持つ値を注入する。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
<property name="name" value="mkyong"/>
<property name="type" value="txt"/>
</bean>
</beans>
3. “p”スキーマ
“p”スキーマを属性として使用して値を注入する。
<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-2.5.xsd">
<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator"
p:name="mkyong" p:type="txt"/>
</beans>
忘れずに
xmlns:p = “http://www.springframework.org/schema/p
“をSpring XML Bean設定ファイルに宣言してください。