带注释的控制器中的动态命令类


问题内容

从Spring MVC
3开始,AbstractCommandController已弃用,因此您不再可以在中指定命令类setCommandClass()。而是将命令类硬编码在请求处理程序的参数列表中。例如,

@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request, @ModelAttribute("employee") Employee employee)

我的问题是我正在开发一个通用页面,该页面允许用户编辑通用bean,因此直到运行时才知道命令类。如果变量使用beanClass持有命令类,则AbstractCommandController只需执行以下操作,

setCommandClass(beanClass)

由于我不能将命令对象声明为方法参数,有什么办法可以让Spring将请求参数绑定到请求处理程序主体中的通用bean?


问题答案:

命令对象的实例化是Spring需要知道命令类的唯一地方。但是,您可以使用@ModelAttribute-annotated方法覆盖它:

@RequestMapping(method = RequestMethod.POST) 
public void show(HttpServletRequest request, 
    @ModelAttribute("objectToShow") Object objectToShow) 
{
    ...
}

@ModelAttribute("objectToShow")
public Object createCommandObject() {
    return getCommandClass().newInstance();
}

顺便说一句,Spring还可以与真正的泛型一起正常工作:

public abstract class GenericController<T> {
    @RequestMapping("/edit")  
    public ModelAndView edit(@ModelAttribute("t") T t) { ... }
}

@Controller @RequestMapping("/foo")
public class FooController extends GenericController<Foo> { ... }