Skip to main content

Basic Annotations in Spring Boot

Annotations are the key components. Spring Boot annotations are simple and self-explanatory. There are a large number of annotations are implemented in Spring  Core. But In Spring Boot most of the annotations are enhanced and combined in simpler ones to write fewer lines of code.

For example: If you are ever worked with spring core you need to apply @Configuration, @EnableAutoConfiguration and @ComponentScan. Now In Spring Boot, these three are combined into @SpringBootApplication .

Here we have listed 32 annotations and explained, in brief, what every beginner should know. If you understand the use and start playing with these annotations no one can stop you to become a master in spring boot. We will provide the detailed example later on so please subscribe to this blog from the footer section by providing an email id:

1.@SpringBootApplication

This is a very first annotation that is applied in each Spring Boot application starter class. It is automatically applied when you initialize your project through Spring Initializr.

2.@Component

The @Component  annotation is used to denote a class as Component. It means that Spring framework will autodetect these classes for dependency injection when annotation-based configuration and classpath scanning is usedThe controllers, services and repositories are its specialization.

3.@Service

The @Service annotation is specialization of @Component, is used with classes that is used to implement some business logic. Spring Boot context will autodetect these classes when auto configuration is performed.

4.@Repository

The @Repository annotation indicates that the class deals with CRUD operations, usually it’s used with DAO implementations that deal with database tables. It is also a specialization of @Component.

5.@Controller

This annotation indicates that an annotated class is a web controller and returns view (page) in response. This annotation serves a specialization of @Component, allowing for implementation classes to be auto detected through classpath scanning.

It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.

6.@RestController

This annotation indicates that an annotated class is a REST controller. Behaves similar to @Controller but it returns data in response. It is used to make REST APIs applications that are named as web-services.

7.@Autowired

The @Autowired annotation is used to inject bean object of the type from the container. We know when application starts a single bean object of every component, service, repository, etc are created into the container. If more than one bean of the same type is available in the container, the framework will throw a fatal exception. So it is handled by container i.e. auto wiring is done. This can be applied to field, constructor and methods. This annotation allows us to implement constructor-based, field-based or method-based dependency injection in our components.

8.@RequestMapping

This is a class level and method level annotation that is used to define request path and request method. It is used in and along with both @Controller and @RestController. Example  is shown above and below to represent both combination.

9.@GetMapping

@GetMapping is used to handle GET requests. Instead of using @RequestMapping("/home", method = RequestMethod.GET) simply use @GetMapping("/home")

10.@PostMapping

@PostMapping is used to handle post requests. POST method is used to create new resource. Instead of using @RequestMapping("/add-student", method = RequestMethod.POST) simply use @PostMapping("/add-student").

11.@PutMapping

@PutMapping annotation is used to handle put requests. PUT method is used to update the existing resource. Instead of using @RequestMapping("/update-student/<student_id>", method = RequestMethod.PUT) simply use @PutMapping("/update-student/<student_id>").

Note: POST and PUT methods work similarly. It's up to you how you use them. The name is different because to identify the requests that how they will affect our data.

12.@DeletMapping

The @DeleteMapping annotation is used to handle delete requests. Delete method is used to delete the existing resource. Instead of using @RequestMapping("/delete-student/<student_id>", method = RequestMethod.DELETE) simply use @GetMapping("/delete-student/<student_id>").

13.@RequestBody

The @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the incoming HttpRequest body onto a Java object

14.@ResponseBody

 The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

15.@RequestParam

http://localhost:8080/book?isbn=1234 here isbn is a request parameter

The @RequestParam annotation is used to read the form data or request parameter from HttpRequest object and bind it automatically to the variable in provided method. So, it ignores the requirement of HttpServletRequest object to read the parameter values.

16.@PathParam

ws://localhost:8080/book?isbn=1234 here isbn is a path parameter for websocket request 

The @PathParam annotation is used to read websocket request and binds the data similar to @RequestParam. The only difference is @PathParm is used with websocket request and @RequestParam is used with HttpRequest parameter. 

17.@PathVariable

http://localhost:8080/book/{isbn} here isbn is a path variable

The @PathVariable annotation identifies the pattern that is used in the URI for the incoming request.

18.@Value

The @Value  annotation is used to read application properties values that are present in application.properties.

19.@PostConstruct

The @PostConstruct annotation is used on method inside a component class(annotated with @Component, @Service, @Repository, @Controller) to execute before they start serving the service.

Annotations related to Data Persistency

20.@Entity

The @Entity  annotation defines that a class can be mapped to a table. And that is just a marker, like for example interface. It takes class name as a table name by default also provides option to write custom names with name attribute like @Entity(name="student_result"). The class which is annotated with this annotation is called as entity class.

21.@Id

The @Id annotation is used to make a field as a primary key inside the entity class. It is must to make a class as entity.

22.@GeneratedValue

The @GeneratedValue annotation is used to generate value with different type of pattern. Mostly used in combination with @Id annotation to make auto generated primary keys.

23.@Column

The @Column annotation is used over every data members inside a entity class to set the column attributes like unique, or not null. It is optional by default JPA makes the variable name as a table field.

24.@Transient

The @Transient annotation is used to exclude a field that does not have to be appeared in table.

25.@JsonIgnore

The fields that are annotated with @JsonIgnore are not serialized with entity object is returned throug API/Ajax calls.

26.@Enumerated

When we need to save enum values into database table we use @Enumerated over enum field of the entity.

27.@PrePersist

The @PrePersist annotation is used on methods of the entity which is executed just before saving the data for the first time into the database.

28.@PreUpdate

The @PreUpdate annotation is used on methods of the entity which is executed just before updating the existing data in the database.

29.@OneToOne

The @OneToOne annotation is applied on a field to define relation between one entity class with another entity class, Internaly it saves primary key of the second entity as a foriegn key. For example  if one employee must have one address; conditions applied with an entity employee with second entity address - employee entity contains name, email, mobile number, and address contains  village, landmark, city, district, state, pincode, etc.

30.@OneToMany

The @OneToMany is also an relation mapping annotation. As its name is self explaining. For example  one department has many employees.

31.@ManyToOne

The @ManyToOne is just reverse of @OneToMany annotation. For example many students belongs to one class.

32.@ManyToMany

The @ManyToMany is when many objects of one entity belongs to many objects of second entity. For examples one teacher teaches many class a day and one class is taught my many teachers a day.

Thanks for reading the article. We will provide you detailed examples of each annotation very soon. That will increase your confidence.

Popular posts from this blog

How to Implement AWS RDS Database IAM Authentication in Spring Boot

Amazon RDS for MySQL allows authentication using AWS Identity and Access Management (IAM) database authentication. With this authentication method, you don't need to use a password when you connect to a DB instance. Instead, you use an authentication token. Let us understand how this works? An authentication token is a unique string of characters that Amazon RDS generates on request. Authentication tokens are generated using AWS Signature Version 4. Each token has a lifetime of 15 minutes. You don't need to store user credentials in the database, because authentication is managed externally using IAM. You can also still use standard database authentication. Since IAM authentication tokens are short-lived access tokens that are valid for 15 minutes. For the RDS database this token works as a database password that is required to establish a connection and does not determine how long the existing connection can last. The default value for connection to be alive without activit

How to upload files in Amazon S3 Bucket using Spring Boot

As stated in the title, we are going to demonstrate that how we can upload and retrieve files from the amazon s3 bucket in spring boot. For this, we must have an account on amazon web services (AWS) . And the next thing you need to have is an IAM user that has programmatic access to the s3 bucket. Follow the steps below to create an IAM user and s3 bucket. Table of Contents 1. Steps to create an IAM user in AWS with S3 bucket full access permission Step 1.1 Login to your AWS account   Step 1.2 Set the user details Step 1.3 Set user permissions Step 1.4 Create a user group and set the access policy Step 1.5 Add user to the group Step 1.6  Set the tags (optional) Step 1.7  Review the user details and permission summary Step 1.8 Download the user credentials 2. See, how to create s3 bucket. Step 2.1 Click on the "Create bucket" button. Step 2.2 Enter the bucket name and select bucket region. Step 2.3 Set file accessibility for bucket items as public/private

What Is SSL Certificate and how it works?

Deep Dive into SSL Certificate What Is an SSL Certificate? SSL (Secure Sockets Layer) is the common name for TLS (Transport Layer Security), a security protocol that enables encrypted communications between two machines. An SSL certificate is a small data file leveraging this security protocol to serve two functions: Authentication – SSL certificates serve as credentials to authenticate the identity of a website. They are issued to a specific domain name and web server after a Certificate Authority, also known as a Certification Authority (CA), performs a strict vetting process on the organization requesting the certificate. Depending on the certificate type, it can provide information about a business or website's identity and authenticate that the website is a legitimate business. Secure data communication - When SSL is installed on a web server, it enables the padlock to appear in the web browser. It activates the HTTPS protocol and creates a secure connection between th

How to Implement Spring Security in Spring Boot

Security Example in Spring Boot Implementation of Spring Security in the Spring Boot application is the key point to learn for spring boot developers. Because Authentication and Authorization are the backbones of the whole application. Getting started with the Spring Security Series, this is the first part, in this article we are going to focus on the authentication part with minimal registration. The implementation of registration flow with email verification, customizing password encoding, and setting up password strengths and rules will be explored in another separate article for each.  This article will be the base of the spring security series, the other security features will be explained on the basis of this implementation, so be focused and let's understand. The code contains proper naming & brief comments that makes it very comprehensive. If you feel any difficulty or find any issue, please drop a comment below this post The main goal of this article is to impleme