Spring 3 MVC: Dependency Injection for annotated Controllers
Declaring controllers via annotations instead of implementing an interface is a pretty neat thing in Spring 3 compared to version 2.5, in my opinion. You get some new flexibility in naming and constructing your Controller classes and in addition you don't have to care about declaring your controller within a spring configuration file.
The Spring documentation explains how to set up an annotation driven controller in chapter 15.3. Basically you annotate your designated controller class with @Controller and then you add a handler method, which gets annoted with
@RequestMapping.@Controller
public class SophoraSampleController {
@RequestMapping(value = "/**")
public String getContent(HttpServletRequest request) {
// do stuff
}
}In order to register your controller to the Spring Dispatcher Servlet, all you have to do is add the following line to your web application's spring configuration.
<context:component-scan base-package="com.subshell.sophora.sample"/>
This line causes Spring to scan the given package for @Controller annotated classes and register them to the Spring Dispatcher Servlet. Done! But what happens if you need to inject beans to your controller?! What happens if "auto-wire" is not an option?!
The answer is simple, but - as far as i know - it is not written down in the Spring documentation explicitly. Due to naming conventions it is still possible to configure your bean within the configuration file, even it was found by "component-scan". The controllers bean id is created automatically by Spring from the class name.
Referring to the SophoraSampleController example, you could add the following bean definition into your Spring configuration file. Certainly your controller needs setter methods for the injected properties. In the following example this would be setSampleValue() and setSampleBean().
<bean id="sophoraSampleController"> <property name="sampleValue" value="1" /> <property name="sampleBean" ref="someBeanId" /> </bean>
Categories
Sophora CMS - A New Take on Content Management
Sophora is optimized to meet the needs of modern companies that produce up-to-date multimedia content on a large scale and that require fast delivery of their content.
Toromiro
Toromiro is a professional tool for the administration and editing of Java Content Repositories (JCR). JCR is powering some of today’s most successful solutions for content management and digital asset management.