Extend annotated controllers in Spring MVC

2020-06-03 02:49发布

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?

2条回答
来,给爷笑一个
2楼-- · 2020-06-03 03:01

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

查看更多
在下西门庆
3楼-- · 2020-06-03 03:18

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

查看更多
登录 后发表回答