Converting a Spring Controller into a @Controller
Join the DZone community and get the full member experience.
Join For FreeIn the Spring Web Framework, its typical to implement a Controller as a class that implements
org.springframework.web.servlet.mvc.Controller, for example:
This class would then be defined within an application's Spring context XML file (typically appname-servlet.xml)
Using Spring annotations however, its possible to remove the need to implement the
org.springframework.web.servlet.mvc.controller and remove the bean definition within the XML file.
org.springframework.web.servlet.mvc.controller and remove the bean definition within the XML file.
To
change the Controller class to use annotations, the class needs to be
annotated with the @Controller and @RequestMapping annotations as shown
below. The method that will handle the request also needs to be
annotated with the @RequestMapping. Note that this method no longer
needs to confirm to the same signature as defined in
org.springframework.web.servlet.mvc.Controller and now simply returns a
ModelAndView instance.
Now
that we've redefined the Controller class, we can remove the bean
definition from the application's context file. The final stage then to
allow Spring to use the annotated Controller is to specify in the
application's context file that we want to use annotations. This is
achieved by adding the <annotation-driven /> annotation into the
application context file.
From http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-controller-into-a-controller.html
Spring Framework
Opinions expressed by DZone contributors are their own.
Comments