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"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/mapping/*">aController</prop>
<prop key="/test/*">testController</prop>
</props>
</property>
</bean>
<!-- 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>
<bean id="testService" class="com.myapp.service.TestService" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
</beans>