Explicitly defining a Spring MVC Annotation-Based Controller

Beginning with Spring MVC 2.5, MVC controllers can be declared using the @Controller annotation. Spring picks up the controller through this declaration in Spring servlet application context:

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

In the past, this has worked perfectly for me, and I have injected dependencies into my controllers using the @Autowired annotation. In my current job, however, we are not doing any annotation-based dependency injection. So, I had to figure out how to explicitly define the controller in the XML so I could inject dependencies in the XML. The solution was to remove the component scanning, keep the @Controller annotation and declare the controller as I would a regular bean in the XML. Here is an example:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
                <prop key="/mapping/*">aController</prop>
                <prop key="/test/*">testController</prop>

    <!-- Controller bean definitions -->
    <bean id="aController" class="com.myapp.controller.AController" />

    <bean id="testController" class="com.aa.car.service.controller.TestController">
        <property name="testService" ref="testService" />

    <bean id="testService" class="com.myapp.service.TestService" />

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

Posted in Java, Spring Tagged with: , ,


Follow Me

RSS FeedFollow me on Twitter