Spring registering custom editor example

0

In Spring Default Editors we saw how spring manages to convert the values for some of the types like Number, Class, Class[], File etc. In this article, I will show you an example of registering a date property editor, to convert a date string to a java.util.Date object.
This example uses the following frameworks:

  1. Maven 3.2.3
  2. Spring 4.1.5.RELEASE
  3. Eclipse  as the IDE, version Luna 4.4.1.

Dependencies

Add the following dependencies:

  1. spring-core
  2. spring-context
  3. spring-beans

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javarticles.spring</groupId>
	<artifactId>springListExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>		
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>

</project>

Registering a property editor

You would register a property editor in the Spring XML context by declaring spring provided bean CustomEditorConfigurer. It is a bean factory post processor bean so configures the property editors right after the bean factory creation and before any of the beans get instantiated. We set the map of custom property editors using the property customEditors. The map contains the type as the key and the property editor bean as the value.
Let’s see an example of date property editor. We need to explicitly register it as by default spring doesn’t support it.

Here is our test bean.

TestBean:

package com.javarticles.spring;

import java.util.Date;


public class TestBean {
    private Date dateValue;

    public Date getDateValue() {
        return dateValue;
    }

    public void setDateValue(Date dateValue) {
        this.dateValue = dateValue;
    }    
}

Let’s configure it in spring context XML.

applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<bean id="testBean" class="com.javarticles.spring.TestBean">
		<property name="dateValue" value="2007-09-01" />
	</bean>
</beans>

If you note, we are setting a date value ‘2007-09-01’. We haven’t registered a property editor so let’s see if spring manages to convert it to a java.util.Date object.

SpringRegisterPropertyEditorExample:

package com.javarticles.spring;

import java.io.IOException;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringRegisterPropertyEditorExample {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {         
            TestBean testBean = (TestBean) context.getBean("testBean");
            System.out.println(testBean.getDateValue());
        } finally {
            context.close();
        }
    }

}

When you run the class, it throws exception:

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

Ok, now let’s register a property editor for the date field.
Spring already provides a custom date editor class CustomDateEditor for converting date strings into java.util.Date.We just need to declare it in the bean configuration file. You need to inject a date format object, to the constructor so that spring can parse the date string.

Once you have declared the bean, you need to register it in a CustomEditorConfigurer instance against customEditors property. It accepts a map of editors. The property editor key would be java.util.Date and value would be the declared date editor dateEditor.

applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

 	<bean id="dateEditor"
		class="org.springframework.beans.propertyeditors.CustomDateEditor">
		<constructor-arg>
			<bean class="java.text.SimpleDateFormat">
				<constructor-arg value="yyyy-MM-dd" />
			</bean>
		</constructor-arg>
		<constructor-arg value="true" />
	</bean>
	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dateEditor" />
				</entry>
			</map>
		</property>
	</bean>
	<bean id="testBean" class="com.javarticles.spring.TestBean">
		<property name="dateValue" value="2007-09-01" />
	</bean>
</beans>

Let’s rerun our main class.

SpringRegisterPropertyEditorExample:

package com.javarticles.spring;

import java.io.IOException;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringRegisterPropertyEditorExample {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {         
            TestBean testBean = (TestBean) context.getBean("testBean");
            System.out.println(testBean.getDateValue());
        } finally {
            context.close();
        }
    }

}

Output:

Jun 08, 2015 10:18:38 AM org.springframework.beans.factory.config.CustomEditorConfigurer postProcessBeanFactory
WARNING: Passing PropertyEditor instances into CustomEditorConfigurer is deprecated: use PropertyEditorRegistrars or PropertyEditor class names instead. Offending key [java.util.Date; offending editor instance: [email protected]e09
Jun 08, 2015 10:18:38 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.s[email protected]6a5fc7f7: defining beans [dateEditor,org.springframework.beans.factory.config.CustomEditorConfigurer#0,testBean]; root of factory hierarchy
Sat Sep 01 00:00:00 IST 2007
Jun 08, 2015 10:18:38 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org[email protected]300ffa5d: startup date [Mon Jun 08 10:18:38 IST 2015]; root of context hierarchy
Jun 08, 2015 10:18:38 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.s[email protected]6a5fc7f7: defining beans [dateEditor,org.springframework.beans.factory.config.CustomEditorConfigurer#0,testBean]; root of factory hierarchy

Download the source code

This was an example about registering a custom editor.

You can download the source code here: springRegisterPropertyEditorExample.zip
Share.

Comments are closed.