Extending annotated controllers in Spring MVC

I am working on a small project and have some existing code that I want to keep clean from my changes, and therefore I need to extend the annotated controller, but this does not work:

package a; @controller public class BaseController { // Autowired fields protected x toExtend() { // do stuff } @RequestMapping(value = "/start") protected ModelAndView setupForm(...) { toExtend(); // more stuff } } package b; @controller public class NewController extends BaseController { // Autowired fields @Override protected x toExtend() { super.toExtend(); //new stuff } } 

Package a and b are scanned for controllers, and I cannot change this. I really did not expect this to work, because @RequestMapping (value = "/ start") is redundant in both controllers. And I get an exception because of this.

So my question is, is it possible to extend the annotation-controlled controller at all without changing the BaseController?

+4
source share
2 answers

You can extend one spring controller with another spring controller.

When the spring MVC controller extends another controller, the functionality of the base controller can be directly used by the child controller using the request URL of the child controller. You can get more details here Extension of spring controllers

+7
source

If the BaseController annotation cannot be removed, you can use the adapter template to receive inheritance.

 @Controller public class NewController { // Autowired fields BaseController base; protected x toExtend() { base.toExtend(); //new stuff } } 

In normal cases, either BaseController does not have the @Controller annotation, so common controller methods can be placed inside BaseController to be expanded by actual controllers

+2
source

All Articles