找不到默认构造函数; 嵌套异常是使用Spring MVC的java.lang.NoSuchMethodException?

joh*_*ohn 22 java model-view-controller spring 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

}
Run Code Online (Sandbox Code Playgroud)

每当我启动服务器时,我都会遇到异常 -

No default constructor found; nested exception is java.lang.NoSuchMethodException:
Run Code Online (Sandbox Code Playgroud)

但是,如果我删除TestController构造函数,那么它没有任何问题.我在这做什么错?

但是,如果我添加这个默认构造函数,那么它开始工作正常 -

    public TestController() {

    }
Run Code Online (Sandbox Code Playgroud)

Ric*_*lla 37

Spring无法实例化您的TestController,因为它的唯一构造函数需要一个参数.您可以添加无参数构造函数,也可以将@Autowired注释添加到构造函数中:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您明确告诉Spring在应用程序上下文中搜索KeeperClient bean并在实例化TestControlller时将其注入.


pra*_*kre 18

如果要创建自己的构造函数,则必须定义no-args或default构造函数.

您可以阅读为什么需要默认或不需要参数构造函数.

为什么默认有或无参数的构造函数,Java的class.html

  • 感谢您的回复,这个问题是我自己问的,但我还没有得到正确的答案。 (2认同)

MK *_*ung 7

在我的情况下,Spring抛出了这个错误,因为我忘记了将内部类静态化。

当您发现即使添加无参数构造函数也无济于事时,请检查您的修饰符。


IKo*_*IKo 7

在我的情况下,我忘记@RequestBody在方法参数中添加注释:

public TestController(@RequestBody KeeperClient testClient) {
        TestController.testClient = testClient;
    }
Run Code Online (Sandbox Code Playgroud)