Spring Annotations

Spring Boot Annotations with features, project, starter project wizard, cli, application, annotations, dm, properties, actuator, thymeleaf view, jpa, jdbc

Spring Annotations

Spring Annotations

Here, we will discuss about the annotations that we have used in our project.

Note - The @RestController and @RequestMapping annotations are Spring MVC annotations. They are not specific to Spring Boot.

The @RestController and @RequestMapping annotations

The @RestController is a stereotype annotation. It adds @Controller and @ResponseBody annotations to the class. We need to import org.springframework.web.bind.annotation package in our file, in order to implement it.

In our controller class. It can be used like:

  1. package com.tpoint;  
  2. import org.springframework.web.bind.annotation.RestController;  
  3. @RestController  // using @RestController annotation  
  4. public class HomeController {  
  5.     // controller body  
  6. }  

The @RestController annotation informs to the Spring to render the result back to the caller.

The @RequestMapping annotation is used to provide routing information. It tells to the Spring that any HTTP request should map to the corresponding method. We need to import org.springframework.web.annotation package in our file.

As in the following example, we have a method hello() which should map with /hello url.

  1. package com.tpoint;  
  2. import org.springframework.web.bind.annotation.RequestMapping;  
  3. import org.springframework.web.bind.annotation.RestController;  
  4. @RestController  
  5. public class HomeController {  
  6.     @RequestMapping("/hello")  
  7.     public String hello(){  
  8.         return"Hello!";  
  9.     }  
  10.  

You can also specify a request method in @RequestMapping annotation as we have done in the following example.

  1. package com.tpoint;  
  2. import org.springframework.web.bind.annotation.RequestMapping;  
  3. import org.springframework.web.bind.annotation.RestController;  
  4. @RestController  
  5. public class HomeController {  
  6.     @RequestMapping(value = "/hello", method = "GET")  
  7.     public String hello(){  
  8.         return"Hello!";  
  9.     }  
  10. }  

A GET request by localhost:8080/hello url will map to the hello() method.