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.
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 .
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] @GetMapping is used to handle GET requests. Instead of using @RequestMapping(“/home”, method = RequestMethod.GET) simply use @GetMapping(“/home”).
[email protected] @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”).
[email protected] @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.
[email protected] 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>”).
[email protected] 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
[email protected] The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
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.
[email protected] 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.
[email protected] The @Value annotation is used to read application properties values that are present in application.properties.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] The @Transient annotation is used to exclude a field that does not have to be appeared in table.
[email protected] The fields that are annotated with @JsonIgnore are not serialized with entity object is returned throug API/Ajax calls.
[email protected] When we need to save enum values into database table we use @Enumerated over enum field of the entity.
[email protected] 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.
[email protected] The @PreUpdate annotation is used on methods of the entity which is executed just before updating the existing data in the database.
[email protected] 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.
[email protected] The @OneToMany is also an relation mapping annotation. As its name is self explaining. For example one department has many employees.
[email protected] The @ManyToOne is just reverse of @OneToMany annotation. For example many students belongs to one class.
[email protected] 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.