原文地址:http://howtodoinjava.com/spring/spring-core/registering-built-in-property-editors-in-spring-4-customeditorconfigurer-example/

A property editor is a feature of the JavaBeans API for converting property values to and from text values. Each property editor is designed for a certain type of property only. You may wish to employ property editors to simplify your bean configurations. In this tutorial, we will learn to configure spring’s build-in CustomDateEditor class into your application.

CustomEditorConfigurer and CustomDateEditor configurations

Normally, you will register a property editor in the container before it may be used. The CustomEditorConfigurer class is implemented as a built-in bean factory post processor for you to register your custom property editors before any of the beans get instantiated.

For example, in your application if you want to convert date values from string format to java.util.Date objects or vice-versa, you can use CustomDateEditor class. The CustomDateEditor class that comes with Spring is for converting date strings into java.util.Date properties.

CustomEditorConfigurer bean can be declared into application context as below:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <bean class="com.howtodoinjava.demo.processors.CustomDateEditorRegistrar" />
        </list>
    </property>
</bean>

CustomDateEditorRegistrar class should be declared in below manner from spring 4.x onwards.

public class CustomDateEditorRegistrar implements PropertyEditorRegistrar
{
    public void registerCustomEditors(PropertyEditorRegistry registry)
    {
        registry.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }
}

CustomDateEditor Example

Now everytime, when you pass a bean property value (of type java.util.Date) in string format e.g. 2007-09-30, it will be automatically converted to date object.

Let’s Test the configuration. To test, I have created a EmployeeDTO bean having one date field as dateOfBirth.

public class EmployeeDTO {
     
    private Integer id;
    private String firstName;
    private String lastName;
    private String designation;
    private Date dateOfBirth;
 
    //Setters and Getters
 
    @Override
    public String toString() {
        return "EmployeeDTO [id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + ", designation=" + designation
                + ", dateOfBirth=" + dateOfBirth + "]";
    }
}

It’s bean definition in applicationContext.xml file is as below:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <bean class="com.howtodoinjava.demo.processors.CustomDateEditorRegistrar" />
        </list>
    </property>
</bean>
 
<!-- employeeDTO bean -->
<bean id="employeeDTO" class="com.howtodoinjava.demo.model.EmployeeDTO">
    <property name="firstName" value="Lokesh" />
    <property name="lastName" value="Gupta" />
    <property name="designation" value="Manager" />
    <property name="dateOfBirth" value="2007-09-30" />
</bean>

Let’s fetch the bean from context. It should have it’s dateOfBirth filed populated with given date value.

public class TestSpringContext
{
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
        EmployeeDTO employeeDTO = (EmployeeDTO) context.getBean("employeeDTO");
         
        System.out.println(employeeDTO.getDateOfBirth());
    }
}
 
Output:
 
Sun Sep 30 00:00:00 IST 2007

Great. Date value is set.

Happy Learning !!

Spring 4 CustomEditorConfigurer Example--转的更多相关文章

  1. spring源码:学习线索(li)

    一.spring xml配置(不包括AOP,主要了解在初始化及实例化过程中spring配置文件中每项内容的具体实现过程,从根本上掌握spring) <bean>的名字 &,alia ...

  2. Spring ApplicationContext 简解

    ApplicationContext是对BeanFactory的扩展,实现BeanFactory的所有功能,并添加了事件传播,国际化,资源文件处理等.   configure locations:(C ...

  3. Spring学习笔记之二----基于XML的Spring AOP配置

    在Spring配置文件中,通常使用<aop:config>元素来设置AOP,其中应包括: <aop:aspect>指定aspect,aspect是一个POJO类,包含了很多的a ...

  4. spring入门教程——笔记

    Spring学习笔记(1)----简单的实例 ---------------------------------   首先需要准备Spring包,可从官方网站上下载.   下载解压后,必须的两个包是s ...

  5. Spring知识点总结大全(1)

    1.Spring的分层结构 1.Presentation layer(表示层) (1) 表示逻辑(生成界面代码) (2) 接收请求 (3) 处理业务层抛出的异常 (4) 负责规则验证(数据格式,数据非 ...

  6. springMvc源码学习之:spring源码总结

    转载自:http://www.cnblogs.com/davidwang456/p/4213652.html spring beans下面有如下源文件包: org.springframework.be ...

  7. Spring(三)Bean继续入门

    一.Aware相关接口 对于应用程序来说,应该尽量减少对Sping Api的耦合程度,然而有些时候为了运用Spring所提供的一些功能,有必要让Bean了解Spring容器对其进行管理的细节信息,如让 ...

  8. Spring的属性编辑器

    bean类 import java.util.Date; public class Bean { private Date date; public Date getDate() { return d ...

  9. Spring的BeanFactoryPostProcessor和BeanPostProcessor

    转载:http://blog.csdn.net/caihaijiang/article/details/35552859 BeanFactoryPostProcessor和BeanPostProces ...

随机推荐

  1. 自己主动化測试程序之中的一个自己定义键盘的模拟測试程序(C语言)

    一.測试程序编写说明 我们做的终端设备上运行的是QT应用程序.使用自己定义的键盘接口.经过測试人员长时间的人机交互測试,来确认系统的功能是否满足需求. 如今须要编写一个自己主动化的測试程序,能够依照预 ...

  2. Spring中@Transactional事务回滚(含实例具体解说,附源代码)

    一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用. 以下举个栗子:比方一个部门里面有非常多成员,这两者分别保存在部门表和成员表里面,在 ...

  3. int *p,cons int *p,int const *p,int * const p,const int * const p,int const * const p的差别

     加有constkeyword的几种情况的辨析 const修饰的代码 含义(特点) 等价性 int *p = &num; 1.       能够读自己 2.       能够通过*p改自己 ...

  4. 1.RunLoop是什么?

    1.Run loops是线程相关的的基础框架的一部分. 一个run loop就是一个事件处理的循环.用来不停的调度工作以及处理输入事件.使用run loop的目的是让你的线程在有工作的时候忙于工作.而 ...

  5. setsockopt 设置socket

    1.closesocket(一般不会立即关闭而经历TIME_WAIT的过程)后想继续重用该socket:BOOL bReuseaddr=TRUE;setsockopt(s,SOL_SOCKET ,SO ...

  6. python 提取主域名和子域名代码——先根据规则提取,如果有问题,则使用tldextract

    import tldextract def extract_domain(domain): suffix = {'.com','.la','.io', '.co', '.cn','.info', '. ...

  7. nyoj--814--又见拦截导弹(动态规划+贪心)

    又见拦截导弹 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 大家对拦截导弹那个题目应该比较熟悉了,我再叙述一下题意:某国为了防御敌国的导弹袭击,新研制出来一种导弹拦截系 ...

  8. 14.boost最小生成树 kruskal_min_spainning_tree

    #include <iostream> #include <boost/config.hpp> //图(矩阵实现) #include <boost/graph/adjac ...

  9. C#post调用接口并上传文件

    /// <summary> /// C#调用接口上传json数据,并且带文件上传 /// </summary> /// <param name="url&quo ...

  10. JS基本功 | JavaScript专题之数组 - 方法总结

    Array.map() 1.   map() 遍历数组 语法: let new_array = arr.map(function callback(currentValue, index, array ...