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

我正在使用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 } 

每当我启动服务器时,我都会遇到exception –

 No default constructor found; nested exception is java.lang.NoSuchMethodException: 

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

但是,如果我添加这个默认构造函数然后它开始工作正常 –

  public TestController() { } 

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

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

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

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

 @Autowired public TestController(KeeperClient testClient) { TestController.testClient = testClient; } 

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

在我的情况下,spring扔了这个因为我忘了让一个内在的静态。

当你发现它甚至没有帮助添加一个无参数构造函数时,请检查你的修饰符。