i am working on a small project and have some existing code which I want to keep clean from my changes and therefore I need to extend a 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 cannont change this. I did not really expect this to work because the @RequestMapping(value = "/start") is redundant in both controllers. And I get an exception because of this.
So my question is whether it is actually possible to extend a annotation driven controller like this without changing the BaseController?
You can extend one spring controller by another spring controller.
When a 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 Extending Spring controllers
If
BaseController
's annotation cannot be removed, then you can use Adapter Pattern to obtain the inheritance.In usual cases, either
BaseController
does not have@Controller
annotation, hence common controller methods can be put insideBaseController
to be extended by actual controllers