2

I'm trying to register a global InitBinder using an @InitBinder annotated method inside a @ControllerAdvice class.

package com.myapp.spring.configuration;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@ControllerAdvice
@EnableWebMvc
public class CustomInitBinder {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        System.out.println("INIT BINDER");
        binder.registerCustomEditor(java.sql.Date.class, new SqlDatePropertyEditor());
        binder.registerCustomEditor(java.sql.Timestamp.class, new SqlTimestampPropertyEditor());
    }

}

The problem I'm having is that I see it finding the @InitBinder when loading, but it never actually enters the method because I don't get the "INIT BINDER" printed to System.out. This means that the custom editors aren't getting registered, and as such they don't work. If I copy and paste the initBinder method into one of my Controllers it works just fine for that specific Controller.

1989  INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] (RequestMappingHandlerAdapter.java:636) - Detected @InitBinder methods in customInitBinder

Any ideas what's going on here?

Paul
  • 133
  • 2
  • 9
  • Just wondering if you actually can mix ControllerAdvice and EnableWebMvc? – Martin Frey Feb 21 '14 at 00:46
  • I can't remember where I saw someone else doing the same thing - but removing it doesn't seem to make a difference. – Paul Feb 21 '14 at 00:55
  • Most likely this is a class scanning issue. ControllerAdvice has to be loaded in the same ApplicationContext as the Controllers. As your advice is in a config package, are you sure it's initialized by spring into the servlect-context? – Martin Frey Feb 21 '14 at 06:33
  • My component scan is in the root-context.xml, is this not where I should put it? I have package names such as com.myapp.spring.controllers com.myapp.spring.configuration and my XML file has the following – Paul Feb 23 '14 at 23:12

1 Answers1

2

So for anyone coming across this issue... Here's what I did to resolve it.

Instead of having

<context:component-scan base-package="com.myapp.spring"></context:component-scan> 

in my root-context.xml

I changed this to my configuration package

<context:component-scan base-package="com.myapp.spring.configuration"></context:component-scan>

I then moved the @ControllerAdvice annotated class to com.myapp.spring.controllers, and in in servlet-context.xml added

<context:component-scan base-package="com.myapp.spring.controllers">
    <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
Paul
  • 133
  • 2
  • 9