Discover how a simple annotation saves you from endless URL typing and mistakes!
Why @RequestMapping for base paths in Spring Boot? - Purpose & Use Cases
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.
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.
@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.
@GetMapping("/api/users") public List<User> getUsers() { ... } @GetMapping("/api/products") public List<Product> getProducts() { ... }
@RestController @RequestMapping("/api") public class ApiController { @GetMapping("/users") public List<User> getUsers() { ... } @GetMapping("/products") public List<Product> getProducts() { ... } }
This makes your code easier to maintain and update, especially when many endpoints share the same base path.
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.
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.