我的 Spring 应用程序遇到问题,我试图接收一个 boolean 值属性,我使用了对象 boolean 值,但收到此错误:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.lang.Boolean]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.lang.Boolean.<init>()
这就是我创建 Controller 方法的方式:
protected String method(Model model,
@ModelAttribute("attr1") Object1 attr1,
@ModelAttribute("attr2") Object2 attr2,
@RequestParam MultiValueMap<String, String> values,
@ModelAttribute("theattrthatdoesnotwork") Boolean theattrthatdoesnotwork) {
我做错了什么吗?你不能使用 boolean 值作为模型属性吗?,我对 Spring 有点陌生。
提前致谢!
最佳答案
尝试使用@RequestParam Boolean theattrthatdoesnotwork
而不是@ModelAttribute
。当您有 5 个字段并且您不想将所有字段都写为 @RequestParam
时,@ModelAttribute
就有意义。你的错误正在告诉你确切的问题。如果参数没有默认的构造函数
(并且Boolean
显然没有它),则不能使用@ModelAttribute
注释参数。如果您想将 Boolean
作为 body
而不是 param
传递,您应该使用 @RequestBody
而不是 @ModelAttribute
。您可以注意到 attr1
也显示在 url
中。
关于java - 将 ModelAttribute 与 boolean 对象一起使用时找不到默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429448/