2

是否可以让@ModelAttribute 方法只为特定的处理程序方法调用,并只为一个处理程序方法调用提供命令对象?不是针对特定控制器中的每个处理程序方法?我正在使用spring web-portlet MVC,但它应该是一样的......

因为对于一个控制器中的每个处理程序方法调用都会调用此 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);
                }
            }
4

1 回答 1

3

如果您需要这种级别的细粒度控制,那么您需要重构您的代码,即将处理程序方法移动到它自己的类中。Spring MVC 使这变得非常容易,对这种重构应该没有限制。

于 2010-11-13T11:04:58.717 回答