How to fix 404 error in Spring Boot

Published

There are a few common reasons why you may get a 404 error in your Spring Boot application. I have put together a few of the most common reasons below:

Your path parameter types don’t match

@PUT
@Path("some/{dynamic}/path/{here")
public ResponseEntity<Object> doSomething(
    @PathParam("foo") String foo, 
    @PathParam("bar") Integer bar) {
        ...
    }

If you try and access this path using Curl, you will get a 404 - Page Not Found error returned by Spring and Jersey.

curl --location --request PUT 'http://localhost:8080/some/abcde/path/zyx'

This is because the type of the second path parameter is an Integer but a String value was passed in the url. Make sure that your path parameter types match the values being passed to the URL.

Your Jersey Resource Config isn’t registered

If you are using Jersey (or any other JAX-RS specific implementation) in your Spring Boot app to serve resources, you need to register your controller class files. You can do this in Spring by creating a Configuration class that extends ResourceConfig like so:

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyResourceConfig extends ResourceConfig {

    public MyResourceConfig() {
        super();
        registerClasses(MyController.class); // <-- register your controller class like this
    }
}

Your context path is wrong

Double check that your path being served by your controller is correct.

You can define the path at the controller location using the @Path annotation like so:

@Path("/home")
public class MyController {
    ...
}

Additionally, you should check your Application.properties or Application.yaml file to be sure that you aren’t configuring a context-path:

server.servlet.context-path=/some/path-prefix

You should note that this context-path can also be set using an environment variable, a command line argument, or even a WebServerFactoryCustomizer bean.

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWeServerFactory> webServerFactoryCustomizer() {
    return factory -> factory.setContextPath("/some-path");
}