Spring自动类型转换 博客分类: Spring基础 spring类型转换
程序员文章站
2024-02-13 13:04:40
...
(1)要转换的是下列类中的date属性。
package convert; import java.util.Date; public class Student { private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
(2)、写转换的方法,继承PropertyEditorSupport类,覆写setAsText()方法。
package util; import java.beans.PropertyEditorSupport; import java.text.SimpleDateFormat; import java.util.Date; public class DateConvert extends PropertyEditorSupport{ private String format; @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try{ Date date = sdf.parse(text); this.setValue(date); }catch(Exception ex){ ex.printStackTrace(); } } public void setFormat(String format){ this.format = format; } }
3、在Spring的配置文件中,将上面的转换器注册成bean。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd"> <bean id="Student" class="convert.Student" > <property name="birthday" value="2010-1-1"></property> </bean> <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date"> <bean class="util.DateConvert"> <property name="format" value="yyyy-MM-dd"></property> </bean> </entry> </map> </property> </bean> </beans>
(4)测试类。
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import convert.Student; import junit.framework.TestCase; public class StudentTest extends TestCase{ public void testStudent(){ ApplicationContext ctx = new ClassPathXmlApplicationContext( "convert.xml"); Student stu = (Student)ctx.getBean("Student"); System.out.print(stu.getBirthday()); } }
关于这个内容可以参考这个跟详细的博客:spring--类型转换器