Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<context:component-scan> not picking up my @RequestMappings if handler mappings defined in XML

I'm using Spring 3.0.5 with <context:component-scan> and @RequestMapping annotations on my controllers. This works, and URLs are registered by the package scan.

But there is a problem when I have a handler mapping defined in the XML config. The @RequestMapping annotations are no longer picked up.

I've isolated the problem to a simple application.

If I have the following controller:

package test.pack.age;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping(value="/test")
    public String showTestPage() {
        return "testPage";
    }
}

and the following configuration:

<context:component-scan base-package="test.pack.age" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>

The application works correctly and the URL /test is registered and works properly.

18/09/2011  20:02:55    org.springframework.web.servlet.handler.AbstractUrlHandlerMapping   INFO    Mapped URL path [/test] onto handler 'testController'
18/09/2011  20:02:55    org.springframework.web.servlet.handler.AbstractUrlHandlerMapping   INFO    Mapped URL path [/test] onto handler 'testController'

But if I add a handler mapping to the XML it no longer works. Even something simple like this:

<bean id="handlerMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" />

which basically does nothing, and the <context:component-scan> no longer registers my URL.

I need an extra handler mapping for some (third party) controllers which I can't annotate, but when adding it it breaks all my @RequestMappings.

Is this normal? A bug? (I can't change the Spring version)

Am I missing something?

like image 542
ElenaT Avatar asked Oct 10 '22 23:10

ElenaT


1 Answers

Is this normal? A bug? (I can't change the Spring version)

Am I missing something?

I was missing something :D. Found this buried in the Spring's JavaDocs for DefaultAnnotationHandlerMapping:

NOTE: If you define custom HandlerMapping beans in your DispatcherServlet context, you need to add a DefaultAnnotationHandlerMapping bean explicitly, since custom HandlerMapping beans replace the default mapping strategies.

Added this to my config XML and now everything works:

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
like image 97
ElenaT Avatar answered Oct 13 '22 10:10

ElenaT