00 - Spring Boot Annotations Guide
Overview
Spring Boot uses annotations extensively to configure components, define HTTP endpoints, inject dependencies, validate data, manage transactions, and control application behavior.
Annotations reduce boilerplate code and allow developers to declaratively configure the application.
This guide covers the most common Spring Boot annotations used when building REST APIs.
Controller Layer Annotations
@Controller
What is it?
@Controller marks a class as a Spring MVC controller.
It is mainly used in applications that return views such as HTML pages generated by Thymeleaf or JSP.
Example
@Controller
public class EmployeeController {
@GetMapping("/employees")
public String employees(Model model) {
model.addAttribute(
"employees",
employeeService.findAll()
);
return "employees";
}
}
The return value:
return "employees";
is interpreted as a view name:
employees.html
When to use
Use @Controller for:
- Server-side rendered applications
- Thymeleaf applications
- JSP applications
- Traditional MVC applications
Advantages
- Good integration with server-side rendering
- Clear separation between controller and presentation layer
- Useful when the backend generates HTML pages
Disadvantages
- Not ideal for REST APIs
- Requires additional configuration to return JSON
- Less common in modern frontend/backend separated architectures
@RestController
What is it?
@RestController is used to create REST APIs.
It automatically converts Java objects into HTTP responses, usually JSON.
Internally:
@RestController = @Controller + @ResponseBody
Example
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@GetMapping("/{id}")
public Employee findById(
@PathVariable Long id
) {
return employeeService.findById(id);
}
}
Response:
{
"id": 1,
"name": "John"
}
When to use
Use @RestController for:
- REST APIs
- Microservices
- Mobile application backends
- Frontend integrations
- Backend services
Advantages
- Automatic JSON serialization
- Less boilerplate code
- Standard approach for modern APIs
- Easy integration with frontend applications
Disadvantages
- Not designed for returning HTML pages
- Requires clients to consume API responses
Request Mapping Annotations
@RequestMapping
What is it?
@RequestMapping defines the URL mapping for controllers or methods.
Usually used at class level to define a common API prefix.
Example
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
}
All endpoints inside this controller start with:
/api/employees
Why use it?
Without @RequestMapping:
@GetMapping("/{id}")
Creates:
GET /1
With:
@RequestMapping("/api/employees")
Creates:
GET /api/employees/1
Advantages
- Organizes API endpoints
- Creates consistent URL structures
- Avoids duplicated paths
- Improves API readability
Disadvantages
- Too many nested paths can create long URLs
Example:
/api/company/department/employees/active/list
HTTP Method Annotations
Spring provides specialized versions of @RequestMapping.
They define which HTTP method should be accepted.
@GetMapping
Purpose
Used to retrieve data.
Example:
@GetMapping("/{id}")
public Employee findById(
@PathVariable Long id
) {
}
Request:
GET /employees/10
Use cases
- Retrieve a resource
- Search data
- Get information
@PostMapping
Purpose
Used to create new resources.
Example:
@PostMapping
public Employee create(
@RequestBody Employee employee
) {
}
Request:
POST /employees
Body:
{
"name": "Bruno",
"department": "IT"
}
Use cases
- Create users
- Create orders
- Submit forms
@PutMapping
Purpose
Used for complete resource updates.
Example:
@PutMapping("/{id}")
public Employee update(
@PathVariable Long id,
@RequestBody Employee employee
) {
}
Request:
PUT /employees/10
Use cases
Replace an existing resource completely.
@PatchMapping
Purpose
Used for partial updates.
Example:
@PatchMapping("/{id}")
public Employee updateEmail(
@PathVariable Long id,
@RequestBody EmailRequest request
) {
}
Only changed fields are sent.
Advantages
- Sends only changed data
- More efficient for large objects
Disadvantages
- Requires careful implementation
@DeleteMapping
Purpose
Deletes resources.
Example:
@DeleteMapping("/{id}")
public void delete(
@PathVariable Long id
) {
}
Request:
DELETE /employees/10
Request Data Annotations
@PathVariable
What is it?
Extracts values directly from the URL path.
Example
@GetMapping("/employees/{id}")
public Employee find(
@PathVariable Integer id
) {
}
Request:
GET /employees/10
Value:
id = 10
When to use
Use when identifying a specific resource.
Examples:
GET /users/100
GET /orders/500
GET /products/20
Advantages
- More RESTful URLs
- Easy to understand
- Represents resources clearly
- Better cache behavior
Disadvantages
- Less flexible for filtering
- Can become complex with many parameters
Example:
/users/10/orders/20/products/30
@RequestParam
What is it?
Extracts query parameters from the URL.
Example
@GetMapping("/employees")
public List<Employee> search(
@RequestParam String department
) {
}
Request:
GET /employees?department=IT
When to use
Use for:
- Filtering
- Searching
- Pagination
- Sorting
- Optional parameters
Example:
GET /employees?department=IT&page=2&size=20
Advantages
- Very flexible
- Supports optional values
- Perfect for search operations
Disadvantages
- URLs can become very long
- Less semantic for identifying resources
@RequestBody
What is it?
Maps JSON request payloads into Java objects.
Example
@PostMapping
public Employee create(
@RequestBody Employee employee
) {
}
JSON:
{
"name": "John",
"role": "Developer"
}
When to use
Use when receiving complex objects.
Examples:
- Creating users
- Updating profiles
- Processing forms
Advantages
- Clean API design
- Supports complex structures
- Standard REST approach
Disadvantages
- Requires JSON payload
- Harder to test manually
Dependency Injection Annotations
@Autowired
What is it?
Injects Spring-managed dependencies.
Example:
@Autowired
private EmployeeService service;
Recommended approach
Prefer constructor injection:
private final EmployeeService service;
public EmployeeController(EmployeeService service){
this.service = service;
}
Advantages
- Loose coupling
- Easier unit testing
- Dependencies are explicit
Disadvantages
Field injection can hide dependencies.
Component Annotations
@Component
Purpose
Generic Spring bean.
Example:
@Component
public class EmailValidator {
}
Used for:
- Utility classes
- Helpers
- Generic Spring-managed components
@Service
Purpose
Represents the business logic layer.
Example:
@Service
public class EmployeeService {
}
Responsibilities:
- Business rules
- Application logic
- Data processing
@Repository
Purpose
Represents the persistence layer.
Example:
@Repository
public interface EmployeeRepository {
}
Responsibilities:
- Database communication
- CRUD operations
- Exception translation
Common Spring Boot REST Architecture
Client
|
v
@RestController
|
v
@Service
|
v
@Repository
|
v
Database
Layer Responsibilities
| Layer | Responsibility |
|---|---|
| Controller | Handle HTTP requests and responses |
| Service | Business rules and application logic |
| Repository | Database communication |
| Entity | Database representation |
| DTO | Data transfer between layers |
Best Practices
Resource identification
Use:
@PathVariable
Example:
GET /employees/10
Filtering and searching
Use:
@RequestParam
Example:
GET /employees?department=IT
Sending complex data
Use:
@RequestBody
Example:
POST /employees
Body:
{
"name": "Bruno"
}
API Controller Pattern
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@GetMapping("/{id}")
public Employee findById(
@PathVariable Long id
) {
}
@GetMapping
public List<Employee> search(
@RequestParam String department
) {
}
@PostMapping
public Employee create(
@RequestBody Employee employee
) {
}
}
Summary
| Annotation | Purpose |
|---|---|
@RestController | Creates REST APIs |
@Controller | Creates MVC controllers |
@RequestMapping | Defines URL base path |
@GetMapping | HTTP GET endpoints |
@PostMapping | HTTP POST endpoints |
@PutMapping | HTTP PUT endpoints |
@PatchMapping | HTTP PATCH endpoints |
@DeleteMapping | HTTP DELETE endpoints |
@PathVariable | Reads values from URL path |
@RequestParam | Reads query parameters |
@RequestBody | Reads JSON payload |
@Service | Business logic |
@Repository | Database layer |
@Component | Generic Spring bean |
@Autowired | Dependency injection |