spring如何注入Date类型的属性

如题所述

第1个回答  2013-10-09
当想注入非基本类型的值就得用到属性编辑器。它一般用在类型无法识别,如日期等。先看下没用属性编辑器的情况:public class MyDate { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext( "classpath:com/pb/propertyeditor/applicationContext.xml"); MyDate date = (MyDate) context.getBean("md"); System.out.println(date.getDate()); } } bean id="md" class="com.pb.propertyeditor.MyDate">现在需要的就是定义一个属性编辑器,并在spring中加入public class CustomerProperty extends PropertyEditorSupport { String format; public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } // text为需要转换的值,当为bean注入的类型与编辑器转换的类型匹配时就会交给setAsText方法处理 public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat sdf = new SimpleDateFormat(format); try { this.setValue(sdf.parse(text)); } catch (ParseException e) { e.printStackTrace(); } } }<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <!--配置一个自定义编辑器--> <property name="customEditors"><!--需要编辑的属性类型,是一个map--> <map> <entry key="java.util.Date"> <bean class="com.pb.propertyeditor.CustomerProperty"> <property name="format" value="yyyy-mm-dd" /> <!--注入需要转换的格式--> </bean> </entry> </map> </property> </bean> <bean id="md" class="com.pb.propertyeditor.MyDate"> <property name="date"> <value>2011-1-1</value> </property> </bean> 输出结果:Sat Jan 01 00:01:00 CST 2011本回答被提问者采纳
相似回答