2012-09-26 143 views
0

對於大多數情況,我試圖儘可能地對接口進行編碼。但是我遇到了Spring Controller方法簽名的問題。如果我真的寫使用模型的接口簽名,我最終得到了以下異常:Spring - 在控制器方法中指定模型的實現類

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... 
} 

回答

1

您可以使用@ModelAttribute上的控制器方法來得到實現:

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

完美!這正是我需要的。謝謝。 – Mostfoolish

+0

順便說一句,糾正我,如果我錯了 - 但在接口的方法簽名中有@ModelAttribute註解似乎不起作用。我不得不改變它以將其包含在實現類中。 – Mostfoolish

+0

當搜索@ModelAttribute註解時,Spring MVC會查看已實現的接口。請參閱org.springframework.web.bind.annotation.support.HandlerMethodResolver –

相關問題