
- Spring Boot - Home
- Spring Boot - Introduction
- Spring Boot - Quick Start
- Spring Boot - Bootstrapping
- Spring Tool Suite
- Spring Boot - Tomcat Deployment
- Spring Boot - Build Systems
- Spring Boot - Code Structure
- Spring Beans & Dependency Injection
- Spring Boot - Runners
- Spring Boot - Starters
- Spring Boot - Application Properties
- Spring Boot - Configuration
- Spring Boot - Annotations
- Spring Boot - Logging
- Building RESTful Web Services
- Spring Boot - Exception Handling
- Spring Boot - Interceptor
- Spring Boot - Servlet Filter
- Spring Boot - Tomcat Port Number
- Spring Boot - Rest Template
- Spring Boot - File Handling
- Spring Boot - Service Components
- Spring Boot - Thymeleaf
- Consuming RESTful Web Services
- Spring Boot - CORS Support
- Spring Boot - Internationalization
- Spring Boot - Scheduling
- Spring Boot - Enabling HTTPS
- Spring Boot - Eureka Server
- Service Registration with Eureka
- Gateway Proxy Server and Routing
- Spring Cloud Configuration Server
- Spring Cloud Configuration Client
- Spring Boot - Actuator
- Spring Boot - Admin Server
- Spring Boot - Admin Client
- Spring Boot - Enabling Swagger2
- Spring Boot - Using SpringDoc OpenAPI
- Spring Boot - Creating Docker Image
- Tracing Micro Service Logs
- Spring Boot - Flyway Database
- Spring Boot - Sending Email
- Spring Boot - Hystrix
- Spring Boot - Web Socket
- Spring Boot - Batch Service
- Spring Boot - Apache Kafka
- Spring Boot - Twilio
- Spring Boot - Unit Test Cases
- Rest Controller Unit Test
- Spring Boot - Database Handling
- Securing Web Applications
- Spring Boot - OAuth2 with JWT
- Spring Boot - Google Cloud Platform
- Spring Boot - Google OAuth2 Sign-In
Spring Boot Annotations
This chapter will discuss in detail some of the essential annotations in Spring Boot.
Introduction
Annotations are metadata of your code. Metadata means data about data. They are usually placed on top of class, method or variable declaration. Annotations are some alphanumeric value which start with @. Putting annotations in a class does not affect the compilation or running the program. When annotations are used for configuration, an XML file is not needed.
Annotations @Component, @Configuration, @SpringBootApplication, @EnableAutoConfiguration, @ComponentScan, @AutoConfigurationPackage, @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty have already been discussed on the Spring Boot - Configuration/Autoconfiguration chapter.
How to turn on Spring annotations?
Turn on Spring annotations, add the following <context:annotation-config /> before beans declaration in your XML configuration file.
Annotations
@RestController
@RestController marks a class as controller for RESTful web requests. It combines the functionality of@Controllerand@ResponseBody. Here's what it does:
@Controller− Marks the class as a Spring MVC controller, responsible for handling incoming HTTP requests.
@ResponseBody− Tells Spring to serialize the return value of the controller's method directly into the HTTP response body, typically in formats like JSON or XML.
HTTP Related Annotations
@RequestMapping
@RequestMapping annotation is used to map web requests to specific handler methods in a controller class.It acts as a bridge between the incoming HTTP requests and the methods responsible for handling them. You can specify the HTTP method (GET, POST, PUT, DELETE, etc.) that the method handles using themethodattribute.
With latest version of Spring Boot, the preferred way is shortcut annotations instead of @RequestMapping
@GetMapping− Shortcut for @RequestMapping(method = RequestMethod.GET)
@PostMapping− Shortcut for @RequestMapping(method = RequestMethod.POST)
@PutMapping− Shortcut for @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping− Shortcut for @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping− Shortcut for @RequestMapping(method = RequestMethod.PATCH)
Spring currently supports five types of inbuilt annotations for handling different types of incoming HTTP request methods which are GET, POST, PUT, DELETE, and PATCH.
@PathVariable
@PathVariablebinds a method parameter to a URI template variable. A URI template variable isa parameter within a URI that is enclosed by curly brackets and can be substituted before the URI is resolved.
For example, in the URI template
'/users/{id}/{?query1,query2}'
there are three variables:
id −A required path variable
query1 −An optional query variable
query2 −Another optional query variable
@RequestParam
@RequestParambinds a method parameter to a request parameter.
@RequestBody
@RequestBodybinds a method parameter to the body of the HTTP request.
@ModelAttribute
@ModelAttribute binds a method parameter to a model attribute. In Spring Boot, a model variable is an interface that holds data to be passed from a controller to a view.This interface Model is in org.springframework.ui package.
JPA Related Annotations
@Repository
@Repository marks a class as a data access object(DAO). This class is responsible for CRUD operations on your database.
@Entity
@Entitymarks a class as a JPA entity.
@Id
@Idspecifies the primary key of an entity.
@GeneratedValue
@GeneratedValue specifies how the primary key should be generated.
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
Column maps a field to a database column.
@Transactional
@Transactional marks a method or class as transactional. It ensures that a method (or a whole class) is executed within the context of a transaction. When you mark a method with@Transactional, Spring automatically handles transaction management for that method. When you annotate a method with@Transactional, Spring starts a transaction before the method begins executing.If the method completes successfully (without exceptions), Spring commits the transaction (i.e., saves changes to the database). If an exception occurs, Spring rolls back the transaction. To use@Transactional, you need to configure transaction management in your Spring Boot application. Add@EnableTransactionManagementto your main application class.
Other Important Annotations
@Value
This annotation is used to assign default values to variables and method arguments.It can also be used to inject a property value from a properties file or environment variable.
@EnableCaching
@EnableCaching enables caching support. When you add@EnableCachingto a configuration class, Spring scans the application for methods annotated with caching - related annotations (such as@Cacheable,@CachePut,@CacheEvict, or @Caching).
@EnableAsync
@EnableAsyncenables support for asynchronous method execution. Methods annotated with@Asyncwill run in separate threads, allowing the caller to proceed without waiting for the method to complete.