Why We Use Controller in Spring Boot: A Practical Guide
In this article
We use controllers in Spring Boot to handle incoming HTTP requests and define the application's web interface. The @RestController annotation bridges the gap between client requests and your business logic, automatically converting Java objects into JSON responses without manual serialization code.
What You'll Need
- A Java Development Kit (JDK) version 17 or higher installed.
- An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
- Spring Boot Starter Web dependency added to your project (usually via Maven or Gradle).
- Basic understanding of RESTful API principles and JSON structure.
Step-by-Step
- Create a New Spring Boot Project: Initialize your project using Spring Initializr or your IDE's wizard. Ensure you select the "Spring Web" dependency. This pulls in Tomcat and Spring MVC, which are essential for handling HTTP traffic.
- Define the Controller Class: Create a new Java class in your main package. Annotate this class with
@RestController. This is a convenience annotation that combines@Controllerand@ResponseBody, telling Spring that every method in this class should return data directly rather than looking for a view template. - Map Request Paths: Inside the controller, create methods to handle specific endpoints. Use annotations like
@GetMapping,@PostMapping,@PutMapping, or@DeleteMappingon each method. These map HTTP verbs to your Java methods. For example,@GetMapping("/users")maps GET requests to that URL path to the annotated method. - Inject Dependencies: Avoid creating service instances manually within the controller. Instead, use constructor injection. Define a private final field for your Service class and add a constructor that accepts this service. This promotes loose coupling and makes testing easier by allowing you to mock the service later.
- Implement Business Logic Calls: In your controller method body, call the corresponding method on your injected service. The controller's job is strictly to receive the request, extract parameters, delegate to the service, and return the result. It should not contain complex business rules or database queries.
- Handle Path Variables and Parameters: Use
@PathVariableto extract values from the URL path (e.g.,/users/{id}) and@RequestParamto extract query string parameters (e.g.,?sort=asc). Always validate these inputs if they are critical to security or logic integrity. - Return Response Entities: For full control over HTTP status codes, return a
ResponseEntity<YourObject>. For simple success cases, returning the object directly is sufficient, as Spring defaults to a 200 OK status. UseResponseEntity.ok()for explicit clarity orResponseEntity.created()for POST operations.
Common Mistakes
One frequent error is placing business logic inside the controller. Controllers should remain thin; heavy processing belongs in the Service layer. Another mistake is ignoring exception handling. If a service throws an unchecked exception, Spring returns a generic 500 error. You should implement a global exception handler using @ControllerAdvice to provide meaningful error messages to clients. Additionally, developers often forget to annotate classes with @Component or rely on component scanning incorrectly, causing the controller to be ignored by the Spring context.
Tips
Keep your controllers focused on I/O (Input/Output). They should translate HTTP concepts into Java method calls and vice versa. Use DTOs (Data Transfer Objects) instead of exposing your JPA entities directly to prevent leaking internal database structures and to decouple your API contract from your data model. Enable logging in your controllers to track incoming requests and outgoing responses, which is invaluable for debugging production issues. Finally, use @Valid on request bodies to trigger Bean Validation automatically, ensuring data integrity before it reaches your service layer.
Troubleshooting
If you receive a 404 Not Found error, verify that your controller class is in a package scanned by Spring Boot (typically below the main application class package). Check that your method annotations match the HTTP verb you are testing. If you get a 400 Bad Request, check your JSON payload syntax and ensure your field names match the DTO properties exactly. For 500 Internal Server Errors, review the console logs for stack traces; these usually indicate unhandled exceptions in your service layer. If the controller isn't being recognized at all, ensure you have the correct imports and that the class is not abstract or missing the @RestController annotation.
Frequently Asked Questions
What is the difference between @Controller and @RestController?
@Controller is used for traditional MVC applications where methods return view names (like Thymeleaf templates). @RestController implies that every method returns a domain object rather than a view, serializing it directly to JSON or XML.
Can I use multiple controllers in one Spring Boot application?
Yes. Spring Boot supports multiple controllers. Each controller handles a specific subset of URLs or resources. It is best practice to split them by domain (e.g., UserController, OrderController) to keep code organized.
How do I handle errors globally in a controller?
Use the @ControllerAdvice annotation on a separate class. Define methods within it annotated with @ExceptionHandler to catch specific exceptions thrown by any controller in the application and return a standardized error response.
Do I need to configure anything manually to make controllers work?
No. If you have the spring-boot-starter-web dependency, Spring Boot auto-configures the DispatcherServlet and scans for components. Your controllers will be registered automatically as long as they are in the scanned package.
Is it safe to put database queries directly in a controller?
It is technically possible but strongly discouraged. Controllers should delegate to Service classes. This separation ensures that your business logic is reusable, testable, and that your controller remains lightweight and focused on HTTP concerns.