0

I have two diff POJOs(Bean Classes) and i need to have diff date format for each bean. Do i need to initialize the SimpleDateFormat twice with diff Ids so that my two POJOs can use the two date formats?

<bean id="dateFormatEmployee" class="java.text.SimpleDateFormat">
    <constructor-arg value="mm-dd-yy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="dateFormatUser" class="java.text.SimpleDateFormat">
    <constructor-arg value="dd-mm-yyyy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="employee" class="com.kranti.springcore.Employee">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatEmployee" factory-method="parse">
            <constructor-arg value="12-20-90"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean id="user" class="com.kranti.springcore.User">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatUser" factory-method="parse">
            <constructor-arg value="20-12-1995"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
user808457
  • 11
  • 2

1 Answers1

0

SimpleDateFormat is not a thread safe class and should not be created as a singleton - here is why. As a workaround try putting these formats in a properties file. Inject these formats as necessary in to your code and use it when instantiating the SimpleDateFormat class.

Your properties file could look like:

date.format.user=dd-mm-yyyy
date.format.employee=mm-dd-yy

Lets say you have a service beans which handles employees and users

@Component
public class Employee {

    @Value("${date.format.employee}")
    private String dateFormat; // this will end up with the value mm-dd-yy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}

@Component
public class User {

    @Value("${date.format.user}")
    private String dateFormat; // this will end up with the value dd-mm-yyyy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}
Srikanth Anusuri
  • 664
  • 4
  • 14