Spring MapFactoryBeanの例
‘
MapFactoryBean
‘クラスは、SpringのBean構成ファイルで具体的なMapコレクションクラス(HashMapとTreeMap)を作成する方法を開発者に提供します。
MapFactoryBeanの例を次に示します。実行時にHashMapをインスタンス化し、Beanプロパティに注入します。
package com.mkyong.common; import java.util.Map; public class Customer { private Map maps; //... }
SpringのBean構成ファイル。
<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="CustomerBean" class="com.mkyong.common.Customer"> <property name="maps"> <bean class="org.springframework.beans.factory.config.MapFactoryBean"> <property name="targetMapClass"> <value>java.util.HashMap</value> </property> <property name="sourceMap"> <map> <entry key="Key1" value="1"/> <entry key="Key2" value="2"/> <entry key="Key3" value="3"/> </map> </property> </bean> </property> </bean> </beans>
あるいは、utilスキーマと<util:map>を使って同じことを達成することもできます。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> <bean id="CustomerBean" class="com.mkyong.common.Customer"> <property name="maps"> <util:map map-class="java.util.HashMap"> <entry key="Key1" value="1"/> <entry key="Key2" value="2"/> <entry key="Key3" value="3"/> </util:map> </property> </bean> </beans>
utilスキーマを含めることを忘れないでください。そうしないと、次のエラーが発生します
Caused by: org.xml.sax.SAXParseException: The prefix "util" for element "util:map" is not bound.
それを実行します…
package com.mkyong.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[]args ) { ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); Customer cust = (Customer)context.getBean("CustomerBean"); System.out.println(cust); } }
出力
Customer[maps={Key2=2, Key1=1, Key3=3}]Type=[class java.util.HashMap].... 実行時にHashMapをインスタンス化して顧客のマッププロパティに注入しました。 === ソースコードをダウンロードする ダウンロード - リンク://wp-content/uploads/2010/03/Spring-MapFactoryBean-Example.zip[Spring-MapFactoryBean-Example.zip](5KB) === リファレンス . http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/MapFactoryBean.html[MapFactoryBean Javadoc] link://tag/spring/[spring]