Annotations — part 1

There are multiple annotations supported by Spring boot. But, in this article we will discuss about annotations we use most.

To understand annotation in details, lets create a sample application using below steps:

  1. Lets create a project using Spring Initilizr using link
  2. Fill Group and Artifact detail as com.javadoubts and practice respectively.
  3. Add dependencies as Spring Web and Spring boot actuator as mentioned in below screenshot.
  4. information as mentioned in below screenshot. Add dependencies as Spring Web and Spring boot actuator.

3. Unzip the downloaded file and import in eclipse. It will show below dependencies as part of pom.xml

4. Create a PersonService.java class with @Service annotation. This annotation helps us to create a class to define business logic and can be inject using @Autowired annotation in any of the class.

5. Create a Person.java class with @RestController and @RequestMapping annotations as shown below:

@RestController annotation used to created RESTful web services which can be accessed using http methods like GET, POST, etc. and it is the combination of @Controller and @ResponseBody.

@RequestMapping annotation is used to define header, uri, method type, parameters, path, consume type, etc.

@Autowired annotation is to consume service create as part of PersonServide.java class using @Service annotation.

@RequestParam is used to collect all parameters expecting from request. Parameter can be declare as optional also using required attribute as false mentioned at line number 19.

@PathVariable used to collect value from request URI as mentioned from line number 24 to 27.

@GetMapping used to map HTTP GET request. It mainly used to fetch/get data from server.

@PostMapping used to map HTTP POST request. It mainly used to create a new record in the database.

@PutMapping used to map HTTP PUT request. It mainly used to update record data in the database.

@DeleteMapping used to map HTTP DELETE request. It mainly used to delete record data from the database.

OUTPUT:

Below one will call method at line number 19 from Person.java class

Below one will call method at line number 26 from Person.java class

There are some other annotations which we will discuss in upcoming blog.

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0