Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend annotated controllers in Spring MVC

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?

like image 928
Dennis Ich Avatar asked Apr 09 '13 16:04

Dennis Ich


2 Answers

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

like image 180
Ketan Avatar answered Oct 05 '22 16:10

Ketan


If BaseController's annotation cannot be removed, then you can use Adapter Pattern to obtain the inheritance.

@Controller
public class NewController {
    // Autowired fields
    BaseController base;

    protected x toExtend() {
         base.toExtend();
         //new stuff
    }
}

In usual cases, either BaseController does not have @Controller annotation, hence common controller methods can be put inside BaseController to be extended by actual controllers

like image 37
sanbhat Avatar answered Oct 05 '22 16:10

sanbhat