Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

I am working with Spring MVC controller project. Below is my Controller and I have a constructor declared which I am specifically using for testing purpose.

@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  } 

Whenever I am starting the server, I am getting below exception -

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

But if I remove TestController constructor then it works fine without any problem. What wrong I am doing here?

But if I add this default constructor then it starts working fine -

    public TestController() {      } 
like image 658
john Avatar asked Aug 12 '14 19:08

john


2 Answers

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

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

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

like image 82
Ricardo Veguilla Avatar answered Sep 20 '22 15:09

Ricardo Veguilla


You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

like image 23
prashant thakre Avatar answered Sep 21 '22 15:09

prashant thakre