【问题标题】:How instantiate a concrete class in init binder?如何在 init binder 中实例化具体类?
【发布时间】:2014-02-04 10:45:38
【问题描述】:

我必须将一个抽象类绑定到我的控制器请求处理程序方法。

在我用@ModelAttribute注解方法实例化具体类之前:

@ModelAttribute("obj")
public AbstractObh getObj(final HttpServletRequest request){
    return AbstractObj.getInstance(myType);     
}

但现在我尝试在没有 @ModelAttribute 注释方法的情况下这样做,因为每次调用控制器都会触发模型属性注释方法。

所以我尝试使用 InitBinder自定义编辑器 获得具体类,但它不起作用。

我的初始化活页夹:

@InitBinder(value="obj")
protected void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(AbstractObj.class, new SchedaEditor());
}

还有我的帖子处理程序

@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("obj") AbstractObj obj, final BindingResult bindingResult) {
    //my handler
    }

这是我的ObjEditor

@Override
public void setAsText(final String text) throws IllegalArgumentException {
    try{
        if(text == null){
            setValue(new ConcreteObj());
        }else{
            setValue(objService.findById(Long.valueOf(text)));
        }

    }catch(Exception e) {
        setValue(null);
    }
}

【问题讨论】:

    标签: java spring spring-mvc model-binding


    【解决方案1】:

    @ModelAttribute 只是一个命令对象。它不打算根据请求参数进行各种实现。 WebDataBinder 只是影响如何将所有参数映射到命令字段。 所以 - 使用 AbstractObj 类型的字段创建简单的命令对象。

    public class CommandObject {
    
        private AbstractObj type;
    
        public void setType(AbstractObj type) {
            this.type = type;
        }
    
    }
    

    【讨论】:

    • 对不起,但我不太明白.. 你能解释一下“所以 - 创建一个字符串字段类型的简单命令对象,让它返回你想要的任何其他对象。” ??或者你能贴一段代码吗??
    • 刚刚发现你在映射中使用了服务。做了相应的修改。该字段的类型为 AbstractObj(基类)。此外 - 保留 initBinder。因此,将使用此自定义编辑器注入 AbstractObj 类型的字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多