【问题标题】:Spring Mvc method argumrntsSpring Mvc 方法参数
【发布时间】:2018-07-06 21:32:04
【问题描述】:

我是 Spring MVC 的新手。当我更改以下代码时:

@RequestMapping("/showform")
public String showForm(Model theModel) {

    Student student = new Student();

    theModel.addAttribute("student", student);

    return "student-form";
}

以下代码:

    @RequestMapping("/showform")
public String showForm() {

    Model theModel;

    Student student = new Student();

    theModel.addAttribute("student", student);

    return "student-form";
}

我收到此错误:局部变量 theModel 可能尚未初始化

我的问题是Model theModel 怎么会首先被初始化(作为方法参数)?

【问题讨论】:

  • 调用showForm 方法的任何东西(Spring MVC 基础架构)都已初始化并传入Model 参数。
  • Spring 很神奇,它根据您使用的注解从参数中注入依赖项。所以第一个有效,因为春天给了你价值。

标签: java spring-mvc


【解决方案1】:

这是基本的 Java,与 Spring 无关。局部变量和方法参数的初始化方式不同。

对于方法参数,初始化是隐式的,因为您必须为方法调用赋予一些值。示例:

// Declaration
public String showForm(Model theModel) {
}

// Call
showForm(null);

您不能省略参数,因此方法参数将使用您传递给方法调用的值进行初始化。

对于局部变量,它是不同的。如果您只是在没有任何赋值的情况下声明它,则该变量不会被初始化。以下代码将编译:

public String showForm() {
  // Note the initialization with null!
  Model theModel = null;
  Student student = new Student();
  theModel.addAttribute("student", student);
  return "student-form";
}

无论如何,这当然会在运行时导致 NPE。

【讨论】:

  • Spring MVC 是否调用 showForm 并为模型发送值(我的意思是在 Spring MVC 中调用 showForm)?我明白了,在幕后真正初始化模型的是 Java。感谢您的回答
  • 是的,Spring 在调用控制器方法(那些使用@RequestMapping 注释的方法)时发挥了一些作用。它通过反射 API 查看方法声明,如果找到Model 类型的方法参数,则 Spring MVC 将为该参数传递一个模型实例。这发生在幕后。您可以在控制器方法中简单地依赖它。
猜你喜欢
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多