by BehindJava

Basic Annotations in Spring Boot

Home » springboot » Basic Annotations in Spring Boot

In this tutorial we are going to learn about most used 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.

Annotations

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 .

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 used. The 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/<studentid>”, method = RequestMethod.PUT) simply use @PutMapping(“/update-student/<studentid>”).

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/<studentid>”, method = RequestMethod.DELETE) simply use @GetMapping(“/delete-student/<studentid>”).

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.