Spring:Set注入:基本类型、List、Map、Set、Array、Date类型注入...

8 篇文章 0 订阅

Spring依赖注入有两种:构造器注入与Set注入

其中以Set注入为首选。下面演示几个示例。

Bean类:User

Java代码   收藏代码
  1. package com.lwf.bean;  
  2.   
  3. import java.util.Date;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. public class User {  
  9.   
  10.     private String name;  
  11.     private int age;  
  12.     private List listValues;  
  13.       
  14.     private Map map ;  
  15.     private Set set;  
  16.     private String [] array;  
  17.     private Date date;  
  18.       
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.     public void setName(String name) {  
  23.         this.name = name;  
  24.     }  
  25.     public int getAge() {  
  26.         return age;  
  27.     }  
  28.     public void setAge(int age) {  
  29.         this.age = age;  
  30.     }  
  31.     public List getListValues() {  
  32.         return listValues;  
  33.     }  
  34.     public void setListValues(List listValues) {  
  35.         this.listValues = listValues;  
  36.     }  
  37.     public Map getMap() {  
  38.         return map;  
  39.     }  
  40.     public void setMap(Map map) {  
  41.         this.map = map;  
  42.     }  
  43.     public Set getSet() {  
  44.         return set;  
  45.     }  
  46.     public void setSet(Set set) {  
  47.         this.set = set;  
  48.     }  
  49.     public String[] getArray() {  
  50.         return array;  
  51.     }  
  52.     public void setArray(String[] array) {  
  53.         this.array = array;  
  54.     }  
  55.     public Date getDate() {  
  56.         return date;  
  57.     }  
  58.     public void setDate(Date date) {  
  59.         this.date = date;  
  60.     }  
  61. }  

 applicationContext.xml

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.         xmlns:aop="http://www.springframework.org/schema/aop"  
  6.         xmlns:tx="http://www.springframework.org/schema/tx"  
  7.         xsi:schemaLocation="  
  8.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  9.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  10.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  11.   
  12.   
  13.       
  14.     <bean id="userDaoImp4MySql" class="com.lwf.dao.UserDaoImp4MySql"/>  
  15.     <bean id="userDaoImp4Oracle" class="com.lwf.dao.UserDaoImp4Oracle"/>  
  16.     <bean id="userManager" class="com.lwf.manager.UserManagerImp">  
  17.         <property name="userDao" ref="userDaoImp4Oracle"/>  
  18.     </bean>  
  19.   
  20.   
  21.     <bean id="upperAction" class="com.lwf.action.UpperAction">  
  22.         <property name="message" value="good"/>  
  23.     </bean>  
  24.     <bean id="lowerAction" class="com.lwf.action.LowerAction"/>  
  25.       
  26.     <bean id="user" class="com.lwf.bean.User">  
  27.         <property name="name"><value>zhangdong</value></property>  
  28.         <property name="age" value="23" />  
  29.         <property name="listValues">  
  30.             <list>  
  31.                 <value>list1</value>  
  32.                 <value>list2</value>  
  33.             </list>  
  34.         </property>  
  35.         <property name="array">  
  36.             <list>  
  37.                 <value>array1</value>  
  38.                 <value>array2</value>  
  39.             </list>  
  40.         </property>  
  41.         <property name="map">  
  42.             <map>  
  43.                 <entry>  
  44.                     <key ><value>testCaseName</value></key>  
  45.                     <value>testSpring</value>  
  46.                 </entry>  
  47.                 <entry>  
  48.                     <key ><value>testCaseName1</value></key>  
  49.                     <value>testSpring1</value>  
  50.                 </entry>  
  51.             </map>  
  52.         </property>  
  53.         <property name="set">  
  54.             <set>  
  55.                 <value>set1</value>  
  56.                 <value>set2</value>  
  57.             </set>  
  58.         </property>  
  59.           
  60.     </bean>  
  61.       
  62.       
  63. </beans>  

 测试类:

Java代码   收藏代码
  1. package com.lwf.client;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.context.support.FileSystemXmlApplicationContext;  
  10.   
  11. import com.lwf.bean.User;  
  12.   
  13. public class Client {  
  14.     public static void main(String[] args) {  
  15.     ApplicationContext ctx2 = new FileSystemXmlApplicationContext("/src/applicationContext.xml");  
  16.         User user = (User)ctx2.getBean("user");  
  17.         System.out.println(user.getName() +":"+ user.getAge());  
  18.         List list = user.getListValues();  
  19.         for (int i = 0; i < list.size(); i++) {  
  20.             System.out.println(list.get(i));  
  21.               
  22.         }  
  23.           
  24.         Map map = user.getMap();  
  25.         for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {  
  26.             Map.Entry object = (Map.Entry) iter.next();  
  27.             System.out.println((String)object.getKey() +":"+ (String)object.getValue());  
  28.               
  29.         }  
  30.           
  31.         Set set = user.getSet();  
  32.         for(Iterator iter = set.iterator();iter.hasNext();){  
  33.             String str = (String)iter.next();  
  34.             System.out.println(str);  
  35.         }  
  36.           
  37.         String[] array = user.getArray();  
  38.         System.out.println(array);  
  39.           
  40.     }  
  41. }  

 

说明:上例测试了普通属性的注入,List,Map,Array,Set属性的注入。

测试打印出内容:

Java代码   收藏代码
  1. 2010-05-18 15:56:16,794 INFO [org.springframework.context.support.FileSystemXmlApplicationContext] - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@3e86d0: display name [org.springframework.context.support.FileSystemXmlApplicationContext@3e86d0]; startup date [Tue May 18 15:56:16 CST 2010]; root of context hierarchy  
  2. 2010-05-18 15:56:16,997 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from file [D:\workdirlocal\spring_start\src\applicationContext.xml]  
  3. 2010-05-18 15:56:17,388 INFO [org.springframework.context.support.FileSystemXmlApplicationContext] - Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@3e86d0]: org.springframework.beans.factory.support.DefaultListableBeanFactory@184ec44  
  4. 2010-05-18 15:56:17,450 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@184ec44: defining beans [userDaoImp4MySql,userDaoImp4Oracle,userManager,upperAction,lowerAction,user]; root of factory hierarchy  
  5. zhangdong:23  
  6. list1  
  7. list2  
  8. testCaseName:testSpring  
  9. testCaseName1:testSpring1  
  10. set1  
  11. set2  
  12. [Ljava.lang.String;@1d6776d  

 

好,我们的User类中定义了Date date,现在测试Date类型,现在在applicationContext.xml中加入:

Java代码   收藏代码
  1. <property name="date" value="2010/05/18"></property>  

 

在测试类中加入:

Java代码   收藏代码
  1. System.out.println(user.getDate());  

 

测试结果:

我们会发现报错:

Java代码   收藏代码
  1. Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'date'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found  

 

显然从字符串类型转换为Date类型出错,那么怎么办?

回忆一下Struts中actionForm怎么处理类型转换问题?

http://quicker.iteye.com/admin/blogs/629603

 在spring中。我们采取类似的思路,先自己创建转换器再注册。

转换器继承于java.bean.下面的类:

Java代码   收藏代码
  1. package com.lwf.bean;  
  2.   
  3. import java.beans.PropertyEditorSupport;  
  4. import java.text.ParseException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. public class UtilDatePropertiesEditor extends PropertyEditorSupport {  
  9.   
  10.     private String format ;  
  11.     public void setAsText(String text) throws IllegalArgumentException {  
  12.         SimpleDateFormat sdf = new SimpleDateFormat(format);  
  13.         try {  
  14.             Date dateVal = sdf.parse(text);  
  15.             this.setValue(dateVal);  
  16.         } catch (ParseException e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.           
  20.     }  
  21.       
  22.     public void setFormat(String format){  
  23.         this.format = format;  
  24.     }  
  25.   
  26. }  

 那么怎么注册呢?

我们先看在applicationContext.xml中加入

Java代码   收藏代码
  1. <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
  2.           
  3.     </bean>  

 

按F3查找类org.springframework.beans.factory.config.CustomEditorConfigurer,定位spring源代码到src目录,即可看到CustomEditorConfigurer类的源码

Java代码   收藏代码
  1. /* 
  2.  * Copyright 2002-2008 the original author or authors. 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package org.springframework.beans.factory.config;  
  18.   
  19. import java.beans.PropertyEditor;  
  20. import java.util.Iterator;  
  21. import java.util.Map;  
  22.   
  23. import org.apache.commons.logging.Log;  
  24. import org.apache.commons.logging.LogFactory;  
  25.   
  26. import org.springframework.beans.BeansException;  
  27. import org.springframework.beans.FatalBeanException;  
  28. import org.springframework.beans.PropertyEditorRegistrar;  
  29. import org.springframework.beans.factory.BeanClassLoaderAware;  
  30. import org.springframework.core.Ordered;  
  31. import org.springframework.util.ClassUtils;  
  32.   
  33. /** 
  34.  * {@link BeanFactoryPostProcessor} implementation that allows for convenient 
  35.  * registration of custom {@link PropertyEditor property editors}. 
  36.  * 
  37.  * <p>As of Spring 2.0, the recommended usage is to use custom 
  38.  * {@link PropertyEditorRegistrar} implementations that in turn register 
  39.  * any desired editors on a given 
  40.  * {@link org.springframework.beans.PropertyEditorRegistry registry}. 
  41.  * Each PropertyEditorRegistrar can register any number of custom editors. 
  42.  * 
  43.  * <pre class="code"> 
  44.  * &lt;bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"&gt; 
  45.  *   &lt;property name="propertyEditorRegistrars"&gt; 
  46.  *     &lt;list&gt; 
  47.  *       &lt;bean class="mypackage.MyCustomDateEditorRegistrar"/&gt; 
  48.  *       &lt;bean class="mypackage.MyObjectEditorRegistrar"/&gt; 
  49.  *     &lt;/list&gt; 
  50.  *   &lt;/property&gt; 
  51.  * &lt;/bean&gt;</pre> 
  52.  * 
  53.  * <p>Alternative configuration example with custom editor classes: 
  54.  * 
  55.  * <pre class="code"> 
  56.  * &lt;bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"&gt; 
  57.  *   &lt;property name="customEditors"&gt; 
  58.  *     &lt;map&gt; 
  59.  *       &lt;entry key="java.util.Date" value="mypackage.MyCustomDateEditor"/&gt; 
  60.  *       &lt;entry key="mypackage.MyObject" value="mypackage.MyObjectEditor"/&gt; 
  61.  *     &lt;/map&gt; 
  62.  *   &lt;/property&gt; 
  63.  * &lt;/bean&gt;</pre> 
  64.  * 
  65.  * <p>Also supports "java.lang.String[]"-style array class names and primitive 
  66.  * class names (e.g. "boolean"). Delegates to {@link ClassUtils} for actual 
  67.  * class name resolution. 
  68.  * 
  69.  * <p><b>NOTE:</b> Custom property editors registered with this configurer do 
  70.  * <i>not</i> apply to data binding. Custom editors for data binding need to 
  71.  * be registered on the {@link org.springframework.validation.DataBinder}: 
  72.  * Use a common base class or delegate to common PropertyEditorRegistrar 
  73.  * implementations to reuse editor registration there. 
  74.  * 
  75.  * @author Juergen Hoeller 
  76.  * @since 27.02.2004 
  77.  * @see java.beans.PropertyEditor 
  78.  * @see org.springframework.beans.PropertyEditorRegistrar 
  79.  * @see ConfigurableBeanFactory#addPropertyEditorRegistrar 
  80.  * @see ConfigurableBeanFactory#registerCustomEditor 
  81.  * @see org.springframework.validation.DataBinder#registerCustomEditor 
  82.  * @see org.springframework.web.servlet.mvc.BaseCommandController#setPropertyEditorRegistrars 
  83.  * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder 
  84.  */  
  85. public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered {  
  86.   
  87.     protected final Log logger = LogFactory.getLog(getClass());  
  88.   
  89.     private int order = Ordered.LOWEST_PRECEDENCE;  // default: same as non-Ordered  
  90.   
  91.     private PropertyEditorRegistrar[] propertyEditorRegistrars;  
  92.   
  93.     private Map customEditors;  
  94.   
  95.     private boolean ignoreUnresolvableEditors = false;  
  96.   
  97.     private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();  
  98.   
  99.   
  100.     public void setOrder(int order) {  
  101.       this.order = order;  
  102.     }  
  103.   
  104.     public int getOrder() {  
  105.       return this.order;  
  106.     }  
  107.   
  108.     /** 
  109.      * Specify the {@link PropertyEditorRegistrar PropertyEditorRegistrars} 
  110.      * to apply to beans defined within the current application context. 
  111.      * <p>This allows for sharing <code>PropertyEditorRegistrars</code> with 
  112.      * {@link org.springframework.validation.DataBinder DataBinders}, etc. 
  113.      * Furthermore, it avoids the need for synchronization on custom editors: 
  114.      * A <code>PropertyEditorRegistrar</code> will always create fresh editor 
  115.      * instances for each bean creation attempt. 
  116.      * @see ConfigurableListableBeanFactory#addPropertyEditorRegistrar 
  117.      */  
  118.     public void setPropertyEditorRegistrars(PropertyEditorRegistrar[] propertyEditorRegistrars) {  
  119.         this.propertyEditorRegistrars = propertyEditorRegistrars;  
  120.     }  
  121.   
  122.     /** 
  123.      * Specify the custom editors to register via a {@link Map}, using the 
  124.      * class name of the required type as the key and the class name of the 
  125.      * associated {@link PropertyEditor} as value. 
  126.      * <p>Also supports {@link PropertyEditor} instances as values; however, 
  127.      * this is deprecated since Spring 2.0.7 and will be removed in Spring 3.0. 
  128.      * @param customEditors said <code>Map</code> of editors (can be <code>null</code>)  
  129.      * @see ConfigurableListableBeanFactory#registerCustomEditor 
  130.      */  
  131.     public void setCustomEditors(Map customEditors) {  
  132.         this.customEditors = customEditors;  
  133.     }  
  134.   
  135.     /** 
  136.      * Set whether unresolvable editors should simply be skipped. 
  137.      * Default is to raise an exception in such a case. 
  138.      * <p>This typically applies to either the editor class or the required type 
  139.      * class not being found in the classpath. If you expect this to happen in 
  140.      * some deployments and prefer to simply ignore the affected editors, 
  141.      * then switch this flag to "true". 
  142.      */  
  143.     public void setIgnoreUnresolvableEditors(boolean ignoreUnresolvableEditors) {  
  144.         this.ignoreUnresolvableEditors = ignoreUnresolvableEditors;  
  145.     }  
  146.   
  147.     public void setBeanClassLoader(ClassLoader beanClassLoader) {  
  148.         this.beanClassLoader = beanClassLoader;  
  149.     }  
  150.   
  151.   
  152.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {  
  153.         if (this.propertyEditorRegistrars != null) {  
  154.             for (int i = 0; i < this.propertyEditorRegistrars.length; i++) {  
  155.                 beanFactory.addPropertyEditorRegistrar(this.propertyEditorRegistrars[i]);  
  156.             }  
  157.         }  
  158.   
  159.         if (this.customEditors != null) {  
  160.             for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) {  
  161.                 Map.Entry entry = (Map.Entry) it.next();  
  162.                 Object key = entry.getKey();  
  163.                 Object value = entry.getValue();  
  164.                 Class requiredType = null;  
  165.   
  166.                 try {  
  167.                     if (key instanceof Class) {  
  168.                         requiredType = (Class) key;  
  169.                     }  
  170.                     else if (key instanceof String) {  
  171.                         requiredType = ClassUtils.forName((String) key, this.beanClassLoader);  
  172.                     }  
  173.                     else {  
  174.                         throw new IllegalArgumentException(  
  175.                                 "Invalid key [" + key + "] for custom editor: needs to be Class or String.");  
  176.                     }  
  177.   
  178.                     if (value instanceof PropertyEditor) {  
  179.                         beanFactory.registerCustomEditor(requiredType, (PropertyEditor) value);  
  180.                     }  
  181.                     else if (value instanceof Class) {  
  182.                         beanFactory.registerCustomEditor(requiredType, (Class) value);  
  183.                     }  
  184.                     else if (value instanceof String) {  
  185.                         Class editorClass = ClassUtils.forName((String) value, this.beanClassLoader);  
  186.                         beanFactory.registerCustomEditor(requiredType, editorClass);  
  187.                     }  
  188.                     else {  
  189.                         throw new IllegalArgumentException("Mapped value [" + value + "] for custom editor key [" +  
  190.                                 key + "] is not of required type [" + PropertyEditor.class.getName() +  
  191.                                 "] or a corresponding Class or String value indicating a PropertyEditor implementation");  
  192.                     }  
  193.                 }  
  194.                 catch (ClassNotFoundException ex) {  
  195.                     if (this.ignoreUnresolvableEditors) {  
  196.                         logger.info("Skipping editor [" + value + "] for required type [" + key + "]: " +  
  197.                                 (requiredType != null ? "editor" : "required type") + " class not found.");  
  198.                     }  
  199.                     else {  
  200.                         throw new FatalBeanException(  
  201.                                 (requiredType != null ? "Editor" : "Required type") + " class not found", ex);  
  202.                     }  
  203.                 }  
  204.             }  
  205.         }  
  206.     }  
  207.   
  208. }  

 

我们可以看前面注释部分其实已经告诉我们怎么做了。

就是注入customEditors属性,注意看源代码customEditors属性是一个Map。

那么在applicationContext.xml前面加入:

Java代码   收藏代码
  1. <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
  2.         <property name="customEditors">  
  3.             <map>  
  4.                 <entry key="java.util.Date">  
  5.                     <bean class="com.lwf.bean.UtilDatePropertiesEditor">  
  6.                         <property name="format" value="yyyy/MM/dd"/>  
  7.                     </bean>  
  8.                 </entry>  
  9.             </map>  
  10.         </property>  
  11.     </bean>  

 

注意在注册的同时,我们为UtilDatePropertiesEditor注入了format属性,这个属性可以指定格式。

后面仍然保持代码:

Java代码   收藏代码
  1. <property name="date" value="2010/05/18"></property>  

 测试类代码中打印:System.out.println(user.getDate());

输出为:

Java代码   收藏代码
  1. Tue May 18 00:00:00 CST 2010  

 

好了,现在我想改变格式如改成:2010-05-19。即

Java代码   收藏代码
  1. <property name="date" value="2010-05-19"></property>  

那么顺便修改

 

Java代码   收藏代码
  1. <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
  2.     <property name="customEditors">  
  3.         <map>  
  4.             <entry key="java.util.Date">  
  5.                 <bean class="com.bjsxt.spring.UtilDatePropertyEditor">  
  6.                     <property name="format" value="yyyy-MM-dd"/>  
  7.                 </bean>  
  8.             </entry>  
  9.         </map>  
  10.     </property>  
  11.   </bean>  

 那么打印日期输出:

Java代码   收藏代码
  1. Wed May 19 00:00:00 CST 2010  

 

说明我们的日期转换并注册成功。

 

以上可得:

Java代码   收藏代码
  1. 什么是属性编辑器,其作用?  
  2.     * 自定义属性编辑器,是将spring配置文件中的字符串转换成相应的对象进行注入,spring已经内置了很多类型  
  3.     的编辑器,我们可以自定义自己的属性编辑器  
  4.       
  5. 如何自定义属性编辑器?  
  6.     * 继承PropertyEditorSupport,覆写如下方法(参见UtilDatePropertyEditor.java):  
  7.     public void setAsText(String text) throws IllegalArgumentException  
  8.       
  9.     * 将属性编辑器注册到spring中,参考:applicationContext.xml  

 

对于配置文件有多个,并且名称相似如:

applicationContext-beans.xml

applicationContext-others.xml

那么我们在实例化容器的时候可以这样:

Java代码   收藏代码
  1. BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-*.xml");  
  2.           
  3. User user = (User)factory.getBean("user");  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值