具有继承性的通用Spring MVC控制器

zde*_*sam 13 controller spring-mvc

我可以在Spring MVC中执行以下操作吗?

假设我有一个Base GenericController,如下所示,一个请求映射"/ list"

@Controller
public class GenericController<T>{

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<T> getMyPage(){
        // returns list of T
    }

}
Run Code Online (Sandbox Code Playgroud)

以下是我的两个控制器

@Controller(value = "/page1")
public class Page1Controller extends GenericController<Page1>{

}

@Controller(value = "/page2")
public class Page2Controller extends GenericController<Page2>{

}
Run Code Online (Sandbox Code Playgroud)

现在我将能够访问URL"/ page1/list"和"/ page2/list",其中第一个转到Page1Controller,第二个转到Page2Controller.

Rob*_*bin 15

这是不可能的,已被拒绝,见SPR-10089.我认为这有点令人困惑,此外,除了不同的映射之外,这些方法的行为也不太可能完全相同.但您可以使用委托代替:

public class BaseController<T> {
    public List<T> getPageList(){
        // returns list of T
    }
}

@Controller(value = "/page1")
public class Page1Controller extends BaseController<Page1>{
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<Page1> getMyPage() {
      return super.getPageList();
    }    
}

@Controller(value = "/page2")
public class Page2Controller extends BaseController<Page2>{
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<Page2> getMyPage() {
      return super.getPageList();
    }
}
Run Code Online (Sandbox Code Playgroud)


man*_*ish 6

对于那些寻找与Spring Framework 4.x类似的东西的人来说,OP提供的类​​层次结构是可能的.Github上提供了一个示例应用程序.它允许用户查看书籍列表或杂志列表作为JSON.