Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a Java Date object in Spring xml configuration file?

Consider this simple example -

public class Person
 {
    private String name;
    private Date dateOfBirth;

    // getters and setters here...
 }

In order to initialize Person as a Spring bean, I can write the following.

<bean id = "Michael" class = "com.sampleDomainName.Person">
<property name = "name" value = "Michael" />
</bean>

But in the above bean definition, how can I set the dateOfBirth?

For eg. I want to set the dateOfBirth as

1998-05-07
like image 449
CodeBlue Avatar asked Jun 25 '12 22:06

CodeBlue


People also ask

How do you do annotation based configuration in XML Spring?

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

What is Spring XML configuration file?

XML configuration file format. The correlator-integrated messaging for JMS configuration files use the Spring XML file format, which provides an open-source framework for flexibly wiring together the difference parts of an application, each of which is represented by a bean.

Can we use XML configuration in Spring boot?

Before Spring 3.0, XML was the only way to define and configure beans. Spring 3.0 introduced JavaConfig, allowing us to configure beans using Java classes. However, XML configuration files are still used today. In this tutorial, we'll discuss how to integrate XML configurations into Spring Boot.


1 Answers

Spring inject Date into bean property – CustomDateEditor

This paper give two suggestions:

  1. Factory bean
  2. CustomDateEditor

I suggest the "Factory Bean" because the CustomDateEditor is not supported in Spring 4.0+ and the Factory Bean is easy enough to use.

<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-2.5.xsd">

    <bean id="dateFormat" class="java.text.SimpleDateFormat">
        <constructor-arg value="yyyy-MM-dd" />
    </bean>

    <bean id="customer" class="com.mkyong.common.Customer">
        <property name="date">
            <bean factory-bean="dateFormat" factory-method="parse">
                <constructor-arg value="2010-01-31" />
            </bean>
        </property>
    </bean>

</beans>
like image 101
nkduqi Avatar answered Sep 19 '22 21:09

nkduqi