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" />


About Steve Hanson

Steve is a software developer interested in web development and new technologies. He currently works as a Java consultant at Credera in Dallas, TX.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s