How to Fix 404 Endpoint Not Found in Spring Boot (Production Guide)

Introduction

One of the most common errors developers encounter while building REST APIs is the HTTP 404 Endpoint Not Found response. Unlike an HTTP 500 Internal Server Error, which indicates a server-side failure, a 404 means the requested resource or endpoint could not be located.

Although a 404 appears straightforward, identifying the root cause can be surprisingly difficult in production environments. The endpoint may exist in the codebase but still be inaccessible due to incorrect request mappings, application context paths, Spring Security configuration, API Gateway routing, reverse proxy settings, or deployment issues.

In this comprehensive guide, you’ll learn how Spring Boot resolves incoming requests, understand why 404 errors occur, explore the most common production scenarios, and follow a systematic troubleshooting process to resolve them efficiently.

Prerequisites

Before continuing, you should be familiar with:

  • Java Basics
  • Spring Boot Fundamentals
  • Spring MVC
  • REST APIs
  • Request Mapping

If you’re new to these topics, consider reading these articles first:

Learning Objectives

By the end of this guide, you’ll be able to:

  • Understand how Spring Boot resolves HTTP requests.
  • Diagnose why endpoints return HTTP 404.
  • Fix common request mapping issues.
  • Debug context path and deployment problems.
  • Troubleshoot API Gateway and reverse proxy routing.
  • Apply production best practices to prevent endpoint resolution issues.

Table of Contents

  1. What Is HTTP 404?
  2. How Spring Boot Maps Requests
  3. Common Causes of HTTP 404
  4. Request Mapping Mistakes
  5. Context Path Issues
  6. Component Scanning Problems
  7. API Gateway & Reverse Proxy Issues
  8. Spring Security Considerations
  9. Static Resources vs REST Endpoints
  10. Production Troubleshooting Workflow
  11. Best Practices
  12. FAQs

What Is HTTP 404?

HTTP 404 Not Found indicates that the server received the request successfully but couldn’t locate a matching resource or endpoint.

Example:

GET /api/users/10

HTTP/1.1 404 Not Found

Unlike HTTP 500, a 404 usually indicates that the application couldn’t find a matching request mapping rather than encountering an unexpected exception.

How Spring Boot Maps HTTP Requests

Understanding the request resolution process is essential when troubleshooting 404 errors.

The DispatcherServlet receives every incoming request and delegates it to Spring’s HandlerMapping, which searches for a controller method matching the request path and HTTP method.

Client
↓
Embedded Tomcat
↓
DispatcherServlet
↓
Handler Mapping
↓
Controller
↓
Business Logic
↓
Response

If no matching mapping is found, Spring returns:

HTTP 404 Not Found

For a deeper understanding of this process, see Request Lifecycle in Spring Boot – From Client to Response.

Common Causes of HTTP 404

The most common production causes include:

  1. Incorrect URL.
  2. Missing @RequestMapping.
  3. Wrong HTTP method.
  4. Context path mismatch.
  5. Controller outside component scan.
  6. Application startup failure.
  7. Reverse proxy configuration.
  8. API Gateway routing issues.
  9. Kubernetes Ingress misconfiguration.
  10. Typographical errors in endpoint paths.

Let’s examine each of these in detail.

1. Incorrect Request URL

The simplest and most common cause is requesting the wrong URL.

Controller:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // ...
    }
}

Correct request:

GET /api/users/10

Incorrect requests:

GET /users/10

GET /api/user/10

GET /api/userss/10

All of these return:

HTTP 404 Not Found

How to Verify

  • Check your browser, Postman, or API client.
  • Compare the request path with the controller mapping.
  • Review Swagger/OpenAPI documentation if available.

2. Missing @RequestMapping

A common mistake is forgetting the base mapping.

Incorrect:

@RestController
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // ...
    }
}

Developers often assume the endpoint is:

/api/users/10

However, it is actually:

/10

because no class-level @RequestMapping exists.

Correct implementation:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // ...
    }
}

This clearly defines the endpoint hierarchy and improves readability.

3. Wrong HTTP Method

One of the most overlooked causes of HTTP 404 is calling an endpoint with the wrong HTTP method. Although Spring Boot often returns 405 Method Not Allowed for method mismatches, certain configurations (such as API Gateway rules, reverse proxies, or custom filters) may result in a 404, making the issue harder to identify.

Consider the following controller:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping
    public User createUser(@RequestBody User user) {
        return service.save(user);
    }
}

If the client sends:

GET /api/users

Spring cannot find a matching @GetMapping, and the request fails.

Verify the HTTP Method

Always confirm that the client is using the correct HTTP method.

OperationHTTP Method
Retrieve DataGET
Create ResourcePOST
Update Entire ResourcePUT
Partial UpdatePATCH
Delete ResourceDELETE

When testing with Postman or Swagger, double-check the selected method before investigating deeper.

4. Context Path Misconfiguration

Applications often work correctly in development but fail after deployment because the application’s context path changes.

Development:

server.servlet.context-path=

API URL:

http://localhost:8080/api/users

Production:

server.servlet.context-path=/employee-service

The correct endpoint becomes:

https://company.com/employee-service/api/users

If users continue calling:

https://company.com/api/users

they receive:

HTTP 404 Not Found

Verify the Context Path

Check your configuration:

server.servlet.context-path=/employee-service

Also verify:

  • Docker environment variables
  • Kubernetes ConfigMaps
  • Reverse proxy configuration
  • Spring Profiles (dev, test, prod)

If your application behaves differently across environments, review:

  • Spring Boot Configuration Loading Order
  • How to Use Spring Profiles in Spring Boot
  • Profile-Based Bean Loading in Spring Boot

5. Controller Outside Component Scan

Spring only detects components located within the configured component scan.

Example project structure:

com.example

├── Application.java
├── controller
├── service
└── repository

This works because all packages are beneath the main application class.

However:

com.example

Application.java

com.company.controller

The controller is outside the default scan path.

Result:

No controller bean created
↓
No request mapping registered
↓
HTTP 404

How to Verify

Check the startup logs.

You should see messages similar to:

Mapped "{[/api/users],methods=[GET]}"
onto public UserController.getUsers()

If no mappings appear for your controller, Spring never detected it.

Solution

Move the controller beneath the application’s root package or explicitly configure component scanning.

@SpringBootApplication
@ComponentScan({
    "com.example",
    "com.company.controller"
})
public class Application {
}

Use explicit scanning only when necessary. Keeping all components under a common root package is usually the cleaner approach.

6. Application Failed to Start Correctly

Sometimes developers see a 404 because the application never started successfully.

Example startup failure:

BeanCreationException
↓
Application startup failed
↓
Embedded Tomcat never started

If the server isn’t running, every request naturally fails.

Common startup causes include:

  • Bean creation failures
  • Missing configuration
  • Invalid datasource settings
  • Circular dependencies
  • Port conflicts

Before troubleshooting request mappings, confirm that the application started successfully.

Useful related guides:

  • BeanCreationException in Spring Boot – Common Causes and Production Fixes
  • ApplicationContext Startup Slow in Production
  • How Spring Boot Application Starts – Startup Flow Explained
  • How to Fix Failed to Configure a Datasource Error in Spring Boot

7. Typographical Errors in Request Mapping

Even experienced developers occasionally introduce simple spelling mistakes.

Controller:

@RequestMapping("/customers")

Client request:

GET /customer

Result:

HTTP 404

Other common mistakes include:

  • Singular vs plural (user vs users)
  • Hyphen vs underscore (user-profile vs user_profile)
  • Uppercase vs lowercase (on case-sensitive servers)
  • Missing API version prefix

A consistent naming convention across your APIs helps prevent these issues.

8. Missing API Version Prefix

Production APIs often use versioning.

Controller:

@RequestMapping("/api/v1/users")

Client request:

GET /api/users

Response:

404 Not Found

As your APIs evolve, always ensure clients use the correct version.

This becomes especially important when introducing:

  • /v1
  • /v2
  • /v3

without breaking existing consumers.

9. Spring Security Configuration

Security rules can sometimes make endpoints appear unavailable.

For example, if authentication filters, custom security rules, or reverse proxy configurations intercept requests incorrectly, clients may perceive the endpoint as missing.

Verify:

  • Security configuration
  • Request matchers
  • Authentication filters
  • Authorization rules

When debugging, temporarily enable Spring Security DEBUG logging to understand how requests are processed.

logging.level.org.springframework.security=DEBUG

This provides detailed information about request matching and filter execution.

10. Debugging Endpoint Mappings Using Spring Boot Actuator

One of the fastest ways to diagnose HTTP 404 errors is by verifying whether Spring Boot has actually registered your endpoint.

Many developers assume their controller is loaded because the application starts successfully. However, due to package scanning issues, conditional beans, profile mismatches, or startup failures, the endpoint may never be registered.

Spring Boot Actuator provides an endpoint that lists every mapped URL.

Add the dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Enable the endpoint:

management.endpoints.web.exposure.include=mappings

Open:

GET /actuator/mappings

Example output:

Controller:
UserController

GET
/api/users/{id}

POST
/api/users

DELETE
/api/users/{id}

If your endpoint doesn’t appear here, Spring never registered it.

Common Reasons

  • Controller not scanned
  • Bean creation failed
  • Wrong Spring Profile
  • Conditional bean not loaded
  • Startup exception prevented registration

This endpoint should always be your first stop before changing controller code.

11. API Gateway Routing Issues

In microservice architectures, clients rarely communicate directly with Spring Boot services.

Typical architecture:

                Client
                   │
                   ▼
             API Gateway
                   │
        ┌──────────┴──────────┐
        │                     │
        ▼                     ▼
 User Service          Order Service

Sometimes the Spring Boot application is working perfectly, but the API Gateway forwards requests incorrectly.

Example:

Gateway route:

/api/users/**

Actual Spring Boot endpoint:

/user/**

Result:

404 Not Found

Things to Verify

  • Gateway Route
  • Target URI
  • Path Rewrite Rules
  • Strip Prefix configuration
  • Load Balancer routing

Example Spring Cloud Gateway configuration:

routes:
  - id: user-service
    uri: lb://USER-SERVICE
    predicates:
      - Path=/api/users/**

A single incorrect path rewrite can make every endpoint appear unavailable.

12. Reverse Proxy Configuration (Nginx / Apache)

Many production environments use Nginx or Apache as a reverse proxy.

Incorrect configuration:

location /api {

    proxy_pass http://localhost:8080;

}

Suppose your Spring Boot application expects:

/api/users

but Nginx forwards:

/users

Spring Boot cannot match the request.

Result:

HTTP 404

Always verify:

  • proxy_pass
  • rewrite rules
  • forwarded headers
  • context path
  • trailing slash handling

A mismatch between the proxy configuration and Spring Boot routing is a frequent production issue.

13. Kubernetes Ingress Problems

When deploying Spring Boot applications to Kubernetes, the Ingress controller becomes responsible for routing incoming traffic.

Example:

paths:
- path: /employee

Application endpoint:

/api/users

External request:

https://company.com/api/users

Ingress forwards:

/users

Spring Boot receives:

/users

No matching mapping.

HTTP 404

Troubleshooting Checklist

Verify:

  • Ingress Path
  • Rewrite annotations
  • Service Name
  • Service Port
  • Pod Health
  • Namespace
  • Load Balancer configuration

Many “Spring Boot” 404 errors are actually Kubernetes routing problems.

Production Case Study 1 – Wrong Context Path

Symptoms

Application works locally.

Every production request returns:

404 Not Found

Investigation

Local URL:

localhost:8080/api/users

Production URL:

company.com/api/users

Application configuration:

server.servlet.context-path=/employee

Correct URL:

company.com/employee/api/users

Root Cause

The deployment documentation omitted the context path.

Solution

Update the client application and API Gateway to include the correct base path.

Production Case Study 2 – Controller Not Detected

Developer created:

com.company.api

Main Application:

com.example.Application

Spring Boot only scanned:

com.example.*

No controller bean.

No request mappings.

HTTP 404

Solution

Move controllers under the application’s root package or configure @ComponentScan appropriately.

Production Case Study 3 – Wrong HTTP Method

Controller:

@PostMapping("/login")

Frontend:

GET /login

Developer spent hours debugging request mappings before noticing the frontend used the wrong HTTP method.

Lesson:

Always verify the HTTP method before changing backend code.

Troubleshooting Decision Tree

When an endpoint returns HTTP 404, follow this sequence instead of making random changes.

                  HTTP 404
                      │
          Is Application Running?
              │             │
             No            Yes
              │             │
      Check Startup     Does Endpoint
      Logs & Errors     Exist?
                            │
                  ┌─────────┴─────────┐
                  │                   │
                 No                  Yes
                  │                   │
         Verify Controller     Correct URL?
         Component Scan             │
                             ┌──────┴──────┐
                             │             │
                            No            Yes
                             │             │
                     Fix URL         Correct HTTP Method?
                                          │
                                  ┌───────┴────────┐
                                  │                │
                                 No               Yes
                                  │                │
                           Fix Method      Check Context Path
                                               │
                                      Check Gateway / Proxy
                                               │
                                      Check Actuator Mappings
                                               │
                                        Root Cause Found

Following this workflow saves considerable debugging time during production incidents.

Production Best Practices

✔ Keep all controllers under the application’s root package.

✔ Use consistent URL naming conventions.

✔ Version your APIs (/api/v1, /api/v2).

✔ Document endpoints using OpenAPI/Swagger.

✔ Validate routes using /actuator/mappings.

✔ Avoid hardcoding context paths in frontend applications.

✔ Monitor API Gateway logs.

✔ Include endpoint integration tests in your CI/CD pipeline.

✔ Enable structured request logging.

✔ Review request mappings after every deployment.

Common Mistakes

MistakeImpactBetter Practice
Controller outside component scanEndpoint never registeredKeep packages under the root application package
Wrong URLHTTP 404Verify endpoint path
Wrong HTTP method404/405Match controller annotations
Missing context pathEndpoint unreachableVerify deployment configuration
API Gateway rewrite errorRoute mismatchValidate gateway routes
Ingress path mismatchExternal 404Verify Kubernetes routing
Skipping Actuator mappingsLonger debuggingCheck registered endpoints first

Interview Questions

1. What causes HTTP 404 in Spring Boot?

A 404 occurs when Spring Boot cannot find a matching request mapping for the incoming URL and HTTP method.

2. How does Spring Boot resolve incoming requests?

The DispatcherServlet delegates requests to HandlerMapping, which locates the appropriate controller method.

3. How can you list every registered endpoint?

Use Spring Boot Actuator:

/actuator/mappings

4. Why does an endpoint work locally but not in production?

Common reasons include context path differences, API Gateway routing, reverse proxy configuration, Kubernetes Ingress rules, or Spring Profiles.

5. Can a controller exist in the project but still return HTTP 404?

Yes. If Spring never creates the controller bean because of package scanning, conditional configuration, or startup failures, no request mapping is registered.

Frequently Asked Questions

Why do I get HTTP 404 even though the controller exists?

Ensure the controller is detected by Spring’s component scan and verify that its request mapping appears in /actuator/mappings.

What’s the difference between HTTP 404 and HTTP 405?

  • 404 Not Found: No matching endpoint exists.
  • 405 Method Not Allowed: The endpoint exists, but the client used the wrong HTTP method.

Can Spring Security cause HTTP 404?

Yes. Certain security configurations, custom filters, or reverse proxy rules can make endpoints appear unavailable. Enable Spring Security DEBUG logging to trace request processing.

Why should I use /actuator/mappings?

It shows exactly which request mappings Spring Boot has registered, making it one of the most effective tools for diagnosing 404 issues.

Continue Reading on SpringBootFixes

If you’re troubleshooting Spring Boot production issues, these guides will help:

Conclusion

HTTP 404 Not Found is often perceived as a simple routing error, but in production environments it can stem from a wide range of issues, including incorrect request mappings, missing controllers, context path mismatches, API Gateway routing, reverse proxy configuration, Kubernetes Ingress rules, or application startup failures.

Rather than modifying code immediately, follow a structured troubleshooting process: confirm the application started successfully, verify the request URL and HTTP method, inspect /actuator/mappings, review deployment configuration, and check any routing components in front of your application.

By understanding how Spring Boot resolves requests and applying the production debugging techniques outlined in this guide, you’ll be able to diagnose and resolve HTTP 404 errors quickly, reducing downtime and improving the reliability of your REST APIs.

Leave a Comment

Your email address will not be published. Required fields are marked *