@InitBinder使用属性编辑器中的命令对象...

时间:2012-05-15 16:15:50

标签: spring spring-3

我正在将应用程序从Spring 2.0.7迁移到3.1.1,我遇到了initBinder的问题。我们曾经有类似

的方法
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    MyCommand command = (MyCommand)binder.getTarget();
    binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}

PropertyEditor使用目标。当我将其作为带注释的Controller时,不再调用此方法,因此我添加了@InitBinder注释:

@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    MyCommand command = (MyCommand)binder.getTarget();
    binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}

不幸的是binder.getTarget()只是一些默认对象。 @InitBinder的文档还指出我无法将命令作为参数获取:

  

这样的init-binder方法支持{@link的所有参数   RequestMapping}支持,命令/表单对象除外   相应的验证结果对象。

这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

@InitBinder
protected void initBinder(WebDataBinder binder) {
  MyCommand command = (MyCommand)binder.getTarget();
  binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}

答案 1 :(得分:0)

@RequestMapping
// binder will return MyCommand on getTarget()
public void handleMyCommand(MyCommand c) {  
 ...
}

// initialize command before handleMyCommand method call
@ModelAttribute
public MyCommand initializeMyCommand() {
   // perform initialization.
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
   MyCommand c  = (MyCommand) binder.getTarget();
   binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(c));
}

但是,因为命令未初始化¿为什么你不直接打电话给createEditorFromCommand(new MyCommand())

答案 2 :(得分:0)

可能有点晚了,但仍然 - 这是一种在@InitBinder方法中引用模型(命令)对象的方法:

@InitBinder("commandName")
public void initBinder(WebDataBinder binder) throws Exception {
   CommandClass command = (CommandClass) binder.getTarget();
   binder.registerCustomEditor(Some.class, new SomeEditor(command.getOptions());
}

@ModelAttribute("commandName")
public OrderItem createCommand(HttpServletRequest request) {
   return new CommandClass();
}

放置@InitBinder(“something”)而不仅仅是@InitBinder可能是个好主意。这样就不会多次调用@InitBinder,而只会在遇到配置对象时调用它。