Spring 源码学习(3) —— 增加属性注册编辑器

时间:2024-01-11 13:33:08

创建一个实体类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