创建一个实体类UserManager:

 /**
* @filename: UserManager.java
* @desc 增加属性编辑器功能测试实体类
* @author: Wang Chinda
* @blog http://www.cnblogs.com/goodcheap
* @date: 2018-05-25 9:32
* @version: v1.0
* @copyright: Copyright © 2018 ༄ྂ祸ྂྂ害ོ༘苍ྂྂ生ོ༘࿐ྂ 版权所有
* @modify_history: -
* 20180525 Wang Chinda create
* 20180525 Wang Chinda modify method()
*/
package com.itdoc.learn.source.add.attribute; import java.util.Date; /**
* @desc 增加属性编辑器功能测试实体类
* @author Wang Chinda
* @create 2018-05-25 9:32
*/
public class UserManager { private Date dateValue; public Date getDateValue() {
return dateValue;
} public void setDateValue(Date dateValue) {
this.dateValue = dateValue;
} @Override
public String toString() {
return "UserManager{" +
"dateValue=" + dateValue +
'}';
}
}

 创建配置文件:

 <?xml version="1.0" encoding="UTF-8"?>
<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.xsd"> <bean id="getUserManager" class="com.itdoc.learn.source.add.attribute.UserManager">
<property name="dateValue" value="2018-05-25"/>
</bean>
</beans>

测试:

 /**
* @filename: AtrributeClient.java
* @desc 增加属性编辑器测试客户端
* @author: Wang Chinda
* @blog http://www.cnblogs.com/goodcheap
* @date: 2018-05-25 9:34
* @version: v1.0
* @copyright: Copyright © 2018 ༄ྂ祸ྂྂ害ོ༘苍ྂྂ生ོ༘࿐ྂ 版权所有
* @modify_history: -
* 20180525 Wang Chinda create
* 20180525 Wang Chinda modify method()
*/
package com.itdoc.learn.source.add.attribute; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @desc 增加属性编辑器测试客户端
* @author Wang Chinda
* @create 2018-05-25 9:34
*/
public class AtrributeClient { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("test/add-attribute-editor-test.xml");
UserManager userManager = (UserManager) app.getBean("getUserManager");
System.out.println(userManager);
} }

控制台显示:

五月 25, 2018 9:38:19 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef9b8bc: startup date [Fri May 25 09:38:19 CST 2018]; root of context hierarchy
五月 25, 2018 9:38:19 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [test/add-attribute-editor-test.xml]
五月 25, 2018 9:38:19 上午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3c22fc4c: defining beans [getUserManager]; root of factory hierarchy
五月 25, 2018 9:38:19 上午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3c22fc4c: defining beans [getUserManager]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getUserManager' defined in class path resource [test/add-attribute-editor-test.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateValue'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'dateValue': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.itdoc.learn.source.add.attribute.AtrributeClient.main(AtrributeClient.java:26)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateValue'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'dateValue': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:463)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:494)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:488)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1433)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1392)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 11 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'dateValue': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:264)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:448)
... 17 more

出错原因: UserManager中的dateValue属性是Date类型, 而XML中配置的却是String类型。

Spring针对此问题提供了两种解决方案:

1. 使用自定义属性编辑器

使用自定义属性编辑器, 通过继承PropertyEditorSupport, 重写setAsText方法。

1). 编写自定义的属性编辑器:

 /**
* @filename: DatePropertyEditor.java
* @desc 自定义Date属性编辑器
* @author: Wang Chinda
* @blog http://www.cnblogs.com/goodcheap
* @date: 2018-05-25 9:53
* @version: v1.0
* @copyright: Copyright © 2018 ༄ྂ祸ྂྂ害ོ༘苍ྂྂ生ོ༘࿐ྂ 版权所有
* @modify_history: -
* 20180525 Wang Chinda create
* 20180525 Wang Chinda modify method()
*/
package com.itdoc.learn.source.add.attribute; import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; /**
* @desc 自定义Date属性编辑器
* @author Wang Chinda
* @create 2018-05-25 9:53
*/
public class DatePropertyEditor extends PropertyEditorSupport { private String format = "yy-MM-dd"; public void setFormat(String format) {
this.format = format;
} @Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("text: " + text);
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date date = dateFormat.parse(text);
this.setValue(date);
} catch (ParseException e) {
e.printStackTrace();
}
super.setAsText(text);
}
}

2). 将自定义的属性编辑注册到Spring中:

 <?xml version="1.0" encoding="UTF-8"?>
<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.xsd"> <bean id="getUserManager" class="com.itdoc.learn.source.add.attribute.UserManager">
<property name="dateValue" value="2018-05-25"/>
</bean> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.itdoc.learn.source.add.attribute.DatePropertyEditor"/>
</entry>
</map>
</property>
</bean>
</beans>

 控制台输出:

五月 25, 2018 10:11:34 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef9b8bc: startup date [Fri May 25 10:11:34 CST 2018]; root of context hierarchy
五月 25, 2018 10:11:34 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [test/add-attribute-editor-test.xml]
五月 25, 2018 10:11:34 上午 org.springframework.beans.factory.config.CustomEditorConfigurer postProcessBeanFactory
警告: Passing PropertyEditor instances into CustomEditorConfigurer is deprecated: use PropertyEditorRegistrars or PropertyEditor class names instead. Offending key [java.util.Date; offending editor instance: com.itdoc.learn.source.add.attribute.DatePropertyEditor@6302bbb1
五月 25, 2018 10:11:34 上午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6af93788: defining beans [getUserManager,org.springframework.beans.factory.config.CustomEditorConfigurer#0]; root of factory hierarchy
text: 2018-05-25
UserManager{dateValue=Fri May 25 00:00:00 CST 2018}

 2. 注册Spring自带的属性编辑器CustomDateEditor

 1).定义属性编辑器:

 /**
* @filename: CustomDatePropertyEditor.java
* @desc 实现Spring提供的自定义时间编辑器
* @author: Wang Chinda
* @blog http://www.cnblogs.com/goodcheap
* @date: 2018-05-25 10:18
* @version: v1.0
* @copyright: Copyright © 2018 ༄ྂ祸ྂྂ害ོ༘苍ྂྂ生ོ༘࿐ྂ 版权所有
* @modify_history: -
* 20180525 Wang Chinda create
* 20180525 Wang Chinda modify method()
*/
package com.itdoc.learn.source.add.attribute; import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor; import java.text.SimpleDateFormat;
import java.util.Date; /**
* @desc 实现Spring提供的属性编辑器注册器, 应用CustomDateEditor
* @author Wang Chinda
* @create 2018-05-25 10:18
*/
public class CustomDatePropertyEditor implements PropertyEditorRegistrar { @Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yy-MM-dd"), true));
}
}

2).注册到Spring中

 <?xml version="1.0" encoding="UTF-8"?>
<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.xsd"> <bean id="getUserManager" class="com.itdoc.learn.source.add.attribute.UserManager">
<property name="dateValue" value="2018-05-25"/>
</bean> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.itdoc.learn.source.add.attribute.CustomDatePropertyEditor"/>
</list>
</property>
</bean>
</beans>

此处我换了另一个配置文件。

测试:

 /**
* @filename: AtrributeClient.java
* @desc 增加属性编辑器测试客户端
* @author: Wang Chinda
* @blog http://www.cnblogs.com/goodcheap
* @date: 2018-05-25 9:34
* @version: v1.0
* @copyright: Copyright © 2018 ༄ྂ祸ྂྂ害ོ༘苍ྂྂ生ོ༘࿐ྂ 版权所有
* @modify_history: -
* 20180525 Wang Chinda create
* 20180525 Wang Chinda modify method()
*/
package com.itdoc.learn.source.add.attribute; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @desc 增加属性编辑器测试客户端
* @author Wang Chinda
* @create 2018-05-25 9:34
*/
public class AtrributeClient { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("test/customEditor.xml");
UserManager userManager = (UserManager) app.getBean("getUserManager");
System.out.println(userManager);
} }

GitHub源码: https://github.com/wcd19901010/spring-01

Spring 源码学习(3) —— 增加属性注册编辑器的更多相关文章

  1. Spring源码学习-容器BeanFactory(四) BeanDefinition的创建-自定义标签的解析.md

    写在前面 上文Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签对Spring默认标签的解析做了详解,在xml元素的解析中,Spri ...

  2. Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签

    写在前面 上文Spring源码学习-容器BeanFactory(二) BeanDefinition的创建-解析前BeanDefinition的前置操作中Spring对XML解析后创建了对应的Docum ...

  3. spring源码学习之容器的扩展(一)

    在前面的章节,我们一直以BeanFactory接口以及它的默认实现XmlBeanFactory为例进行解析,但是,spring还提供了另一个接口ApplicationContext,用于扩展BeanF ...

  4. Spring 源码学习 04:初始化容器与 DefaultListableBeanFactory

    前言 在前一篇文章:创建 IoC 容器的几种方式中,介绍了四种方式,这里以 AnnotationConfigApplicationContext 为例,跟进代码,看看 IoC 的启动流程. 入口 从 ...

  5. Spring 源码学习笔记11——Spring事务

    Spring 源码学习笔记11--Spring事务 Spring事务是基于Spring Aop的扩展 AOP的知识参见<Spring 源码学习笔记10--Spring AOP> 图片参考了 ...

  6. Spring源码学习笔记12——总结篇,IOC,Bean的生命周期,三大扩展点

    Spring源码学习笔记12--总结篇,IOC,Bean的生命周期,三大扩展点 参考了Spring 官网文档 https://docs.spring.io/spring-framework/docs/ ...

  7. spring源码学习之路---IOC初探(二)

    作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 上一章当中我没有提及具体的搭 ...

  8. Spring源码学习-容器BeanFactory(二) BeanDefinition的创建-解析前BeanDefinition的前置操作

    写在前面 上文 Spring源码学习-容器BeanFactory(一) BeanDefinition的创建-解析资源文件主要讲Spring容器创建时通过XmlBeanDefinitionReader读 ...

  9. 【目录】Spring 源码学习

    [目录]Spring 源码学习 jwfy 关注 2018.01.31 19:57* 字数 896 阅读 152评论 0喜欢 9 用来记录自己学习spring源码的一些心得和体会以及相关功能的实现原理, ...

随机推荐

  1. php命名空间学习笔记。

    为什么要用命名空间? 在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题: 用户编写的代码 与  PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲 ...

  2. 【Alpha】阶段第四次Scrum Meeting

    [Alpha]阶段第四次Scrum Meeting 工作情况 团队成员 今日已完成任务 明日待完成任务 刘峻辰 获取课程评论接口 增加课程接口 赵智源 整合前端进行部署 整合前端进行部署 肖萌威 编写 ...

  3. ASP.NET MVC5 学习系列之表单和HTML辅助方法

    一.表单 (一)Action和Method特性 Action特性用以告知浏览器信息发往何处,因此,Action特性后面需要包含一个Url地址.这里的Url地址可以是相对的,也可以是绝对的.如下Form ...

  4. 结对作业_Two

    Part 1.前言 (附:本次编码涵盖的所有功能均为java语言实现) 结对项目作业 结对同学高裕翔的博客 个人github传送门 博文pdf链接 Part 2.具体分工 本次的结对作业我们简单的拆分 ...

  5. 01.1 Windows环境下JDK安装与环境变量配置详细的图文教程

    01.1 Windows环境下JDK安装与环境变量配置详细的图文教程 本节内容:JDK安装与环境变量配置 以下是详细步骤 一.准备工具: 1.JDK JDK 可以到官网下载 http://www.or ...

  6. linux 下svn忽略文件

    假设想忽略文件temp 1. cd到temp所在的目录下: 2. svn propedit svn:ignore . 注意:请别漏掉最后的点(.表示当前目录),如果报错请看下面 3. 打开的文件就是忽 ...

  7. mysql中一些表选项

    表选项列表 表选项就是,创建一个表的时候,对该表的整体设定,主要有如下几个: charset = 要使用的字符编码, engine = 要使用的存储引擎(也叫表类型), auto_increment ...

  8. 【bzoj5146】有趣的概率 微积分

    题目描述 "可爱的妹子就像有理数一样多,但是我们知道的,你在数轴上随便取一个点取到有理数的概率总是0,"芽衣在床上自顾自的说着这句充满哲理的话,"诶,柚子,我写完概率论的 ...

  9. BZOJ1564 NOI2009二叉查找树(区间dp)

    首先按数据值排序,那么连续一段区间的dfs序一定也是连续的. 将权值离散化,设f[i][j][k]为i到j区间内所有点的权值都>=k的最小代价,转移时枚举根考虑是否修改权值即可. #includ ...

  10. C++解析(15):二阶构造模式

    0.目录 1.构造函数与半成品对象 2.二阶构造 3.小结 1.构造函数与半成品对象 关于构造函数: 类的构造函数用于对象的初始化 构造函数与类同名并且没有返回值 构造函数在对象定义时自动被调用 问题 ...