是否可以让 @ModelAttribute 方法仅针对特定处理程序方法调用,并仅为一个处理程序方法调用提供命令对象?不是针对特定 Controller 中的每个处理程序方法?我正在使用 spring web-portlet MVC,但它应该是相同的......
因为一个 Controller 内的每个处理程序方法调用都会调用此 for 循环,并且隐式模型会提供给前往 View 的每个请求
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);
}
}
最佳答案
如果您需要这种级别的细粒度控制,那么您需要重构代码,即将处理程序方法移至其自己的类中。 Spring MVC 使这变得非常容易,对这种重构不应该有任何限制。
关于spring-mvc - Spring @ModelAttribute 仅用于一种处理程序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4170851/