0
0
Spring Bootframework~3 mins

Why @RequestMapping for base paths in Spring Boot? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple annotation saves you from endless URL typing and mistakes!

The Scenario

Imagine writing a web app where every controller method needs the full URL path repeated, like '/api/users', '/api/products', '/api/orders'. You have to type '/api' again and again for each method.

The Problem

Manually repeating the base path in every method is tiring and error-prone. If you want to change '/api' to '/service', you must update every method. This wastes time and risks missing some places.

The Solution

@RequestMapping at the class level lets you set a common base path once. Then, each method only adds its specific part. This keeps code clean and easy to update.

Before vs After
Before
@GetMapping("/api/users")
public List<User> getUsers() { ... }

@GetMapping("/api/products")
public List<Product> getProducts() { ... }
After
@RestController
@RequestMapping("/api")
public class ApiController {
  @GetMapping("/users")
  public List<User> getUsers() { ... }

  @GetMapping("/products")
  public List<Product> getProducts() { ... }
}
What It Enables

This makes your code easier to maintain and update, especially when many endpoints share the same base path.

Real Life Example

In a shopping app, all API calls start with '/api'. Using @RequestMapping at the class level means you can change '/api' to '/shop/api' in one place if needed.

Key Takeaways

Repeating base paths manually is slow and error-prone.

@RequestMapping at class level sets a shared base path for all methods.

This keeps code cleaner and easier to maintain.