Spring Boot annotations for interview preparation.
Introduction
Spring Boot simplifies the process of building production-ready applications. One of the key features that make Spring Boot so powerful and easy to use is its extensive use of annotations. In this blog, we will explore various Spring Boot annotations, understand their purposes, and see how they help streamline the development process.
Core Annotations
1. @SpringBootApplication
The @SpringBootApplication
annotation is a crucial component in a Spring Boot application, serving as the entry point and primary configuration mechanism. It combines the functionalities of three core annotations: @EnableAutoConfiguration
, @ComponentScan
, and @Configuration .
2. @Configuration
The @Configuration
annotation in Spring Boot is a key part of the Spring Framework, used to indicate that a class declares one or more @Bean
methods. These beans are managed by the Spring container, meaning Spring will create, configure, and manage the lifecycle of these objects. It also contains configuration logics.
This mode of defining bean using @Bean
via @Configuration
is explicit definition of bean. Implicitly it is done by spring via @ComponentScan
.
3. @ComponentScan
This annotation specifies the packages to be scanned for Spring components such as controllers, services, and repositories.
By default, @ComponentScan
scans the package of the class that declares this annotation and all sub-packages.
Customizing Component Scan
You can customize the component scan by using the @ComponentScan
annotation explicitly.
com.example.service
and com.example.repository
packages for components.4.@EnableAutoConfiguration
@EnableAutoConfiguration
is a key annotation in Spring Boot that enables the framework's auto-configuration feature. This feature automatically configures Spring application context based on the dependencies present in the classpath . It significantly reduces the amount of manual configuration required to set up a Spring application.
Controller Annotations
In Spring Boot, controllers are used to handle web requests. Annotations in Spring Boot help to simplify the development and management of controllers. Here are some key annotations used in Spring Boot controllers:
1.@RestController
This annotation marks a class as a controller that handles incoming HTTP request and return responses in different formats like XML, JSON etc. It is a combination of @Controller
and @ResponseBody
, indicates that the class is a web controller and the return values of methods should be serialized directly to the HTTP response body (e.g., JSON or XML).
2.@Controller
This annotation indicates that a particular class serves the role of a controller in the Spring MVC framework. Instead of returning the values in a JSON/XML format it directly renders a view or a template.
3.@RequestMapping
This annotation is used to map web requests to specific handler methods or classes. It can be applied at the class or method level.
4.@PostMapping
The @PostMapping
annotation in Spring Boot is used to map HTTP POST requests to specific handler methods. It is a shorthand for @RequestMapping(method = RequestMethod.POST)
and is typically used for creating new resources on the server.
Usage
@PostMapping
can be applied to methods in a controller class to specify that the method should handle POST requests for a given URL path. This is commonly used in RESTful APIs for operations like creating a new entity.
5.@GetMapping
@GetMapping
can be applied to methods in a controller class to specify that the method should handle GET requests for a given URL path. It is a shorthand for @RequestMapping(method = RequestMethod.GET)
6.@PutMapping
In Java Spring Boot, @PutMapping
is used to handle HTTP PUT requests, which are typically used to update an existing resource.
It is a shorthand for @RequestMapping(method = RequestMethod.PUT)
7.@PatchMapping
In Java Spring Boot, @PatchMapping
is used to handle HTTP PATCH requests, which are typically used to partially update an existing resource. Unlike PUT, which usually updates the entire resource, PATCH allows for partial updates.
Usage
- Annotation:
@PatchMapping
is used at the method level in a controller class. - Endpoint Mapping: The endpoint to which the PATCH request is mapped is specified in the annotation value.
- Request Body: The partial data to be updated is usually passed in the request body.
- Response: The method typically returns a response entity that indicates the status of the update operation.
Stereotype Annotations
In Spring Framework, stereotype annotations are used to define Spring-managed components and to indicate their roles within the application. These annotations help in the automatic detection of Spring beans during the classpath scanning.
1.@Component
The @Component
annotation in Spring is a core part of the framework's annotation-based configuration model. It is a generic stereotype annotation indicating that an annotated class is a "component" and should be managed by the Spring container as a bean.
2.@Service
The @Service
annotation in Spring is a specialization of the @Component
annotation. It is used to annotate service layer classes, which hold business logic and service-related functionalities. Using @Service
makes your intention clear, as it indicates that the annotated class provides some service.
3.@Repository
The @Repository
annotation in Spring is a specialization of the @Component
annotation which is used to annotate the repository classes which act as an interface to communicate with the database. In actual it makes the intention clear that it is a data access layer.
Data Handling Annotations
1.@RequestBody
Used to indicate that a method parameter should be bound to the body of the HTTP request. It is used to convert the HTTP request body to a Java object.
2.@ResponseBody
Used to indicate that the return value of a method should be written directly to the HTTP response body, typically in JSON or XML format.
Path Variable and RequestParam
@PathVariable
@PathVariable
is used to extract values from the URI path. It is typically used when the value is a part of the URI itself.
The @PathVariable("id")
annotation indicates that the id
parameter in the method signature should be bound to the value of the {id}
placeholder in the URI.
@RequestParam
@RequestParam
is used to extract query parameters from the URL. These are typically used for filtering, sorting, or passing additional parameters.
- Endpoint: This method handles GET requests to
/materials/projectMaterial-entries
. - @RequestParam: The
@RequestParam
annotation extracts thematerialId
query parameter from the URL. - Query Parameter: When a request is made to
/materials/projectMaterial-entries?materialId=some-uuid-value
, thematerialId
value is captured and converted into aUUID
object.
Exception Handling
@ExceptionHandler
The @ExceptionHandler
annotation in Spring Boot is used to define a method that handles specific exceptions thrown by controller methods. When a controller method throws an exception, Spring's exception handling mechanism looks for a method annotated with @ExceptionHandler
that matches the exception type. The matching method is then invoked to handle the exception. This allows developers to define custom responses for different types of exceptions, such as returning specific HTTP status codes, custom error messages, or even complex error responses.
By centralizing exception handling logic within the controller, @ExceptionHandler
helps in maintaining cleaner and more maintainable code. It can be applied at both the controller level and within @ControllerAdvice
for global exception handling across multiple controllers.
@RestControllerAdvice
@RestControllerAdvice
is a specialized version of @ControllerAdvice
in Spring Boot that combines @ControllerAdvice
and @ResponseBody
. It is used to provide global exception handling.
This annotation ensures that any exceptions thrown by REST controllers are handled globally, and the response is written directly to the HTTP response body, typically in JSON or XML format.