【问题标题】:Spring - Specify Implementation class of Model within Controller methodsSpring - 在控制器方法中指定模型的实现类
【发布时间】:2012-09-18 03:38:09
【问题描述】:

在大多数情况下,我都在尝试尽可能多地编写接口代码。但是我遇到了 Spring Controller 方法签名的问题。如果我真的使用模型的接口编写签名,我最终会得到以下异常:

BeanInstantiationException: Could not instantiate bean class[PageModel]: Specified class is an interface

当然,我知道它是一个接口,如果我将它更改为实际的实现类,它就可以正常工作。但是没有办法对接口进行编码吗?一个注解或告诉 Spring 要实例化哪个 bean 的东西?顺便说一句,我正在使用注释配置。

@RequestMapping("SpecificPageController")
public interface PageController {

    @RequestMapping({"", "/load"})
    ModelAndView load(@ModelAttribute("model") PageModel model);
}

@Controller
public class SpecificPageController implements PageController {

    @Override
    public ModelAndView load(final PageModel model) {
    }
}

public interface PageModel {
    ... getters and setters...
}

public class ModelImpl implements PageModel {
    ... variables, getters, setters...
}

【问题讨论】:

    标签: spring model-view-controller model controller


    【解决方案1】:

    您可以在控制器方法上使用@ModelAttribute 来获取实现:

    @ModelAttribute 
    public PageModel getModel() {
        return new SpecificPageModel();
    }
    

    【讨论】:

    • 完美!这正是我所需要的。谢谢。
    • 顺便说一句,如果我错了,请纠正我 - 但是在接口的方法签名中使用 @ModelAttribute 注释似乎不起作用。我不得不对其进行更改以将其包含在实现类中。
    • Spring MVC 在搜索 @ModelAttribute 注释时查看已实现的接口。见 org.springframework.web.bind.annotation.support.HandlerMethodResolver
    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多