Search code examples
javaspring

Spring Framework application only returns 404 errors


Have a very simple class:

@RestController
public class LoggingController {
    @GetMapping("/test")
    public ResponseEntity<String> test() {
        return new ResponseEntity<>("Hello", HttpStatus.OK);
    }
}

When I go to the browser it gives me a 404 error. I added a logger which confirms the requests are getting sent. Not sure why the appropriate handler isn't being called.

Incoming request to /test with method GET

Any ideas?


Solution

  • There are two possible reasons here for the controller to return 404.

    Scuffed structure

    Maybe your Controller resides in a package "above" the main class.

    e.g.

    src/main/java
    |-- controllers
        |-- LoggingControler
    |-- framework
        |-- MainApplication
    

    Why doesn't it work? As per default Spring scans all packages (transitively downwards) starting from the one where the MainApplication resides in.

    Either move the MainApplication to the most outer common package or declare an (additional) @ComponentScan on the MainApplication class which adds the other packages, where othere classes are gathered in the scan.

    src/main/java
    |-- controllers
        |-- LoggingControler
    |-- MainApplication
    

    Context Path

    You might have declared a server.servlet.context-path property in your application.properties.

    e.g.

    server.servlet.context-path=foo
    

    then the path you should query would be: http://localhost:8080/foo/test