Loading

sprin源码解析之属性编辑器propertyEditor

异常信息

Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found

十月 23, 2018 1:40:38 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
資訊: Loading XML bean definitions from class path resource [ApplicationContext.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'useFunctionService' defined in class path resource [ApplicationContext.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 'date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at com.wisely.highlight_spring4.ch1.di.BeanFactoryTest.main(BeanFactoryTest.java:15)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found
	at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476)
	at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
	at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1482)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
	... 6 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found
	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287)
	at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:461)
	... 12 more

造成此异常的原因

当bean中属性被声明非String类型时需要做类型转换

bean

import java.util.Date;

import org.springframework.stereotype.Service;

@Service 
public class UseFunctionService {

    private Date date;

    public Date getDate()
    {
        return date;
    }

    public void setDate(Date date)
    {
        this.date = date;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <bean id="useFunctionService" class="com.wisely.highlight_spring4.ch1.di.UseFunctionService">
        <property name="date" value="2018-10-23"></property>
    </bean>
    <bean id="functionService" class="com.wisely.highlight_spring4.ch1.di.FunctionService">
    </bean>

</beans>

调用代码

import java.util.Date;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

@SuppressWarnings("deprecation")
public class BeanFactoryTest
{
    public static void main(String[] args)
    {
//        BeanFactory bf = new XmlBeanFactory(new ClassPathResource("ApplicationContext.xml"));
        ApplicationContext bf = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UseFunctionService useFunc = (UseFunctionService) bf.getBean("useFunctionService");
        Date date = useFunc.getDate();
        System.out.println(date);
    }
}

特别说明:

  这里必须要用 ApplicationContext 而不是 BeanFactory ,因为是属性编辑器是ApplicationContext 对 BeanFactory 的扩展功能,BeanFactory 实际上是不具备这个功能的,调用的时候会报错.

异常解决

注册springt自带的属性编辑器 CustomDateEditor

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;

public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar
{
    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry)
    {
        registry.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <bean id="useFunctionService" class="com.wisely.highlight_spring4.ch1.di.UseFunctionService">
        <property name="date" value="2018-10-23"/>
    </bean>
    <bean id="functionService" class="com.wisely.highlight_spring4.ch1.di.FunctionService">
    </bean>
    
    <!-- 注册springt自带的属性编辑器 CustomDateEditor-->
    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="propertyEditorRegistrars">
            <list>
                <bean class="com.wisely.highlight_spring4.ch1.di.DatePropertyEditorRegistrar"></bean>
            </list>
        </property>
    </bean>
</beans>

控制台输出

属性编辑器是何时并如何被注册到spring容器中的?

查看AbstractApplicationContext 的 refresh 方法

  • 上文中我们在注册属性编辑时用的是 PropertyEditorRegistrarregisterCustomEditor 方法,与这里的beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));究竟是怎么联系在一起的呢? 进入ResourceEditorRegistrar内部查看一下.

属性编辑器是如何被调用的?

分析报错信息

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)//创建bean
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222) //属性注入,此时bean已被实例化但是没初始化
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523)//类型转换
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476)//转换
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
posted @ 2018-10-23 16:13  Hoonick  阅读(795)  评论(0编辑  收藏  举报