spring-mvc - Spring @ModelAttribute 仅用于一种处理程序方法

标签 spring-mvc command-objects

是否可以让 @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/

相关文章:

angularjs - 401 Unauthorized 由于 CORS 发送请求以获取用户 token 时

Spring MVC - 为什么在部署上下文时出现 NoSuchMethodError 异常?

grails - Grails Command 对象应该放在项目结构中的什么位置?

grails - grails验证嵌套的命令对象不起作用

java - Spring DTO-DAO(资源-实体)映射到哪个应用层 : Controller or Service?

mysql - Hibernate 映射中的 OneToMany 和 ManyToOne

java - spring mvc Controller 内的私有(private)方法是线程安全的

grails - 命令对象仅在 Controller 中,还是可以传递给服务层?

grails - Grails:命令对象, View 模式和条件表单字段?

unit-testing - Grails 1.3.5 Controller 测试空命令对象