2010-11-13 75 views
2

是否可以讓@ModelAttribute方法僅針對特定處理程序方法進行調用,並僅爲一個處理程序方法調用提供命令對象?不是針對特定控制器中的每個處理程序方法?我使用Spring的web portlet的MVC,但它應該是相同的...Spring @ModelAttribute僅適用於一種處理程序方法

因爲這個for循環被每一個信息處理方法調用一個控制器內和內隱提供給每個請求將視圖

for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { 
       Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); 
       Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); 
       if (debug) { 
        logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); 
       } 
       String attrName = AnnotationUtils.findAnnotation(attributeMethodToInvoke, ModelAttribute.class).value(); 
       if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { 
        continue; 
       } 
       ReflectionUtils.makeAccessible(attributeMethodToInvoke); 
       Object attrValue = attributeMethodToInvoke.invoke(handler, args); 
       if ("".equals(attrName)) { 
        Class resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); 
        attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType, attrValue); 
       } 
       if (!implicitModel.containsAttribute(attrName)) { 
        implicitModel.addAttribute(attrName, attrValue); 
       } 
      } 

回答

3

如果您需要此級別的細粒度控制,那麼您需要重構代碼,即將處理程序方法移入其自己的類中。 Spring MVC使這非常簡單,對這種重構不應該有任何限制。

+0

我錯過了它的目的。我們可以簡單地在控制器「MyBean initBean()」中創建一個方法,該方法最終進行初始化並返回我們可以添加到「模型」中的bean實例,並且效果是相同的 – lisak 2010-11-13 17:47:02

相關問題