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
在我的情况下,我忘记@RequestBody在方法参数中添加注释:
public TestController(@RequestBody KeeperClient testClient) {
TestController.testClient = testClient;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84138 次 |
| 最近记录: |