为什么在springboot应用程序中找不到模型bean



我的问题是,对象不是在春天从模型中创建的吗?那么,当它试图在下面的程序中注入时,为什么会出现错误呢?

@Controller
public class ContactController {
private final ContactService service;
private Model model;
public ContactController(ContactService service, Model model) {
this.service = service;
this.model = model;
}
@GetMapping("contact")
public String displayPage() {
model.addAttribute("contact", new Contact());
return "contact";
}
}

更新:但这有效!这意味着bean已经创建。(当然,在我们从构造函数和类中删除模型字段之后(

@GetMapping("contact")
public String displayPage(Model model) {
model.addAttribute("contact", new Contact());
return "contact";
}

错误:

***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.isoft.controllers.ContactController required a bean of type 'org.springframework.ui.Model' that could not be found.

Action:
Consider defining a bean of type 'org.springframework.ui.Model' in your configuration.

该模型不是控制器的依赖项。当方法被调用时,您需要返回一个新的模型。否则,不同的请求都会看到相同的模型(竞争条件、安全问题和所有其他类型的恶劣问题(

@Controller
public class ContactController {
private final ContactService service;
public ContactController(final ContactService service) {
this.service = service;
}
@GetMapping("contact")
public String displayPage() {
final Model model = new Model();
model.addAttribute("contact", new Contact());
return "contact";
}
}

当在构造函数中将模型定义为依赖项时,将在应用程序上下文中查找该类型(和名称(的bean。只注入了一个实例。

但是,该模型是特定于请求的,因此需要注入处理程序方法本身。想想@Scope("request")

@GetMapping("contact")
public String displayPage(final Model model) {
model.addAttribute("contact", new Contact());
return "contact";
}

更多细节可以在SpringWebMVC框架文档中找到:17.3实现控制器

最新更新