Annotations

Spring Boot is a popular framework for building Java-based enterprise applications, including RESTful APIs. Annotations play a crucial role in Spring Boot applications, as they help define the behavior of various components. Here are some common annotations used for creating RESTful APIs in Spring Boot:

  1. @SpringBootApplication:

    • Usage: Main class of the Spring Boot application. It is often placed on the class containing the main method.

    • Example:

      @SpringBootApplication
      public class MyApplication {
          public static void main(String[] args) {
              SpringApplication.run(MyApplication.class, args);
          }
      }
  2. @RestController:

    • Usage: Applied to classes to indicate that they are controllers handling HTTP requests and responses.

    • Example:

      @RestController
      public class MyController {
          // Controller methods here
      }
  3. @RequestMapping (or @GetMapping, @PostMapping, @PutMapping, @DeleteMapping):

    • Usage: Used to map HTTP requests to specific handler methods.

    • Example:

      @RestController
      public class MyController {
          @GetMapping("/hello")
          public String sayHello() {
              return "Hello, World!";
          }
      }
  4. @PathVariable:

    • Usage: Extracts values from URI templates in @RequestMapping annotated methods.

    • Example:

      @GetMapping("/hello/{name}")
      public String sayHello(@PathVariable String name) {
          return "Hello, " + name + "!";
      }
  5. @RequestParam:

    • Usage: Binds parameters from the query string to the method parameters.

    • Example:

      @GetMapping("/greet")
      public String greet(@RequestParam String name) {
          return "Greetings, " + name + "!";
      }
  6. @RequestBody:

    • Usage: Used to bind the HTTP request body to a method parameter.

    • Example:

      @PostMapping("/create")
      public ResponseEntity<String> create(@RequestBody MyEntity entity) {
          // Process the entity and return a response
      }
  7. @ResponseStatus:

    • Usage: Sets the HTTP status code for the response.

    • Example:

      @PostMapping("/create")
      @ResponseStatus(HttpStatus.CREATED)
      public ResponseEntity<String> create(@RequestBody MyEntity entity) {
          // Process the entity and return a response
      }
  8. @CrossOrigin:

    • Usage: Configures Cross-Origin Resource Sharing (CORS) for a controller or a specific method.

    • Example:

      @CrossOrigin(origins = "http://localhost:8080")
      @RestController
      public class MyController {
          // Controller methods here
      }

Depending on your application's requirements, you may need to use additional annotations or customize the behavior of these annotations further.

Last updated