realsim
realsim

Reputation: 1640

Springs CustomDateEditor luring to make mistakes?

Let me start with a couple of facts:

SimpleDateFormat is not thread safe as proven here: Andy Grove's Blog: SimpleDateFormat and Thread Safety

When you want to convert Strings that are parameters of a request to other objects (like java.util.Date) you can use Java Beans' property editor support.

For java.util.Date Spring offers a class that does the conversion for you: CustomDateEditor.

The constructor of that class required a DateFormat as the first argument. So even if the registration of custom property editors happens for each request: With injecting a SimpleDateFormat (the only standard implementation of DateFormat) as suggested here (please scroll down or use your browser's search for SimpleD...), you run into the trap.

What would be a thread safe solution?

Upvotes: 0

Views: 298

Answers (1)

ikumen
ikumen

Reputation: 11653

Configure your SimpleFormatDate with scope="request", a new instance of SimpleDateFormat will be instantiated with each request.

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

Note: you may need to configure it with a proxy

<beans
  xmlns:aop="http://www.springframework.org/schema/aop"
  ...
  xsi:schemaLocation="...
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  <bean id="simpleDateFormat" class="java.text.SimpleDateFormat" scope="request">
    <constructor-arg value="dd-MM-yyyy"/>
    <aop:scoped-proxy />
  </bean>
  ...

Upvotes: 1

Related Questions