Search code examples
javaapispring-bootgradleintellij-14

Spring Api: the program is not finding the pat into the controller


I start my first api project starting by 0. I downloaded the start up project from spring initialiser, and I start to code in it. But now I have a little problem. It seems that the main class don't recognise the controller I created, cause i try to put the code of the controller into the main and it works, in the actual status it give me "Path not found 404" error.

Can It be that I must add the controller somewhere?

Thanks in advance!

Main class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiDispatcherApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiDispatcherApplication.class, args);
    }
}

Controller

import model.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class WebController {

    @Autowired
    public WebController(){

    }

    @RequestMapping(path = "/sample", method = RequestMethod.GET)
    public ApiModel Sample(@RequestParam(value = "name", defaultValue = "Robot") String name){
        ApiModel response = new ApiModel();
        response.setResponse("Your name is " + name);
        return response;
    }
}

In this moment it gives me 404, but if I put the controller code directly in the main class it works


Solution

  • Thank @dassum I solved my problem in this way:

    Main class

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @ComponentScan("controller") //controller is the name of the folder of my controllers
    public class ApiDispatcherApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ApiDispatcherApplication.class, args);
        }
    }
    

    Hope I helped some other starters with this post :)

    Thanks @dassum!