![](/img/trans.png)
[英]No default constructor found; nested exception is java.lang.NoSuchMethodException bean configuration
[英]No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?
我正在使用 Spring MVC 控制器项目。 下面是我的控制器,我声明了一个构造函数,专门用于测试目的。
@Controller
public class TestController {
private static KeeperClient testClient = null;
static {
// some code here
}
/**
* Added specifically for unit testing purpose.
*
* @param testClient
*/
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
// some method here
}
每当我启动服务器时,我都会遇到异常 -
No default constructor found; nested exception is java.lang.NoSuchMethodException:
但是如果我删除TestController
构造函数,那么它可以正常工作,没有任何问题。 我在这里做错了什么?
但是如果我添加这个默认构造函数,那么它开始工作正常 -
public TestController() {
}
Spring 无法实例化您的 TestController,因为它唯一的构造函数需要一个参数。 您可以添加无参数构造函数或向构造函数添加 @Autowired 注释:
@Autowired
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
在这种情况下,您明确告诉 Spring 在应用程序上下文中搜索 KeeperClient bean 并在实例化 TestControlller 时注入它。
就我而言,spring 抛出了这个,因为我忘记将内部类设为静态。
当您发现即使添加无参数构造函数也无济于事时,请检查您的修饰符。
就我而言,我忘记在方法参数中添加@RequestBody
注释:
public TestController(@RequestBody KeeperClient testClient) {
TestController.testClient = testClient;
}
如果您的环境是同时使用Guice和Spring和使用构造@注入,例如,与游戏框架,你也会碰到这个问题,如果你有误自动完成了一个不正确的选择进口:
import com.google.inject.Inject;
然后,即使带有 @Inject 的源代码的其余部分看起来与项目中的其他工作组件完全相同并且编译时没有错误,您也会得到相同的missing default constructor
错误。
用以下方法更正:
import javax.inject.Inject;
不要编写带有构造时间注入的默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.