How can I make initBinder()
method to start every time form loads and submits. This example has responsibility to convert date from String to java.util.Date
.
In my servlet-context.xml:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.example.web.ExampleBindingInitializer" />
</property>
</bean>
Here is my implementation of WebBindingInitializer:
public class ExampleBindingInitializer implements WebBindingInitializer {
private ExampleService exampleService;
@Autowired
public ExampleBindingInitializer(ReservationService reservationService) {
this.reservationService = reservationService;
}
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
I didn't made any modifications in controller where ExampleService methods are called. Where I'm wrong?
When I put initBinder()
method with @InitBinder
annotation to my controller, everything works fine. That doesn't satisfy me beacause I want to have that in external class.
Make sure you have
<mvc:annotation-driven/>
included in your configuration and your bean declared prior to it.When Spring scans for handlers the first registered handler that fits is used.
mvc:annotation-driven
registers a few handlers which may be being used in place of your handler.You must remove or comment out
<mvc:annotation-driven/>
from your dispatcher-servlet. DocumentationThe class,
AnnotationMethodHandlerAdapter
, you use is old and deprecated. You shouldn't use it.I assume you have
<mvc:annotation-driven />
or@EnableWebMvc
which registers the recommended and supportedRequestMappingHandlerAdapter
. You could create aBeanPostProcessor
to set the desired property on theRequestMappingHandlerAdapter
.However what you actually should do is create a custom converter and register that using the
<mvc:annotation-driven />
namespace. That is the recommended way of doing things and not using aWebBindingInitializer
anymore.