Understanding Spring Annotations

Understanding Spring Annotations

Spring Framework came into existence on 1st October 2002. Since then many of its versions have been released and it has become quite a popular framework in the IT industry.

Spring MVC is a Web MVC Framework for building web applications. It follows the traditional method of developing applications. It implements all the basic features of a core spring framework like Inversion of Control and Dependency Injection.

Spring Annotations allow us to configure dependencies and implement dependency injection through java programs in a much easier and more efficient manner. Annotations brought significant changes in programming style and slowly eliminated the XML-based configurations.

What Are Annotations?

Annotations are used to provide supplemental information about a program. It is not a part of the application that we develop neither it has a direct effect on the operation of the code they annotate. These are a form of metadata that provides data about a program. Annotations also do not change the action of the compiled program.

Types of Spring Framework Annotations

There are 6 types of annotation available in the whole spring framework.

  1. Spring Core Annotations

  2. Spring Web Annotations

  3. Spring Boot Annotations

  4. Spring Scheduling Annotations

  5. Spring Data Annotations

  6. Spring Bean Annotations

Some of the vital Spring MVC annotations are:

  1. @Autowired

    @Autowired annotation is applied to the fields, setter methods, and constructors. It injects object dependency implicitly. We use @Autowired to mark the dependency that will be injected by the Spring container.

  2. @Controller

    This is a spring bean annotation. @Controller is a class-level annotation, which tells the Spring IOC container to treat this class as Spring MVC Controller. It marks a class as a web request handler. It is usually used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation.

     @Controller
     public class HomeController {
     }
    
  3. @RequestMapping

    RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. When configuring Spring MVC, you need to specify the mappings between the requests and handler methods. The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. Some of the examples are mentioned below

    • @RequestMapping with Class

        @RequestMapping("/about")
        public class AboutController {
        //Code Here
        }
      
    • @RequestMapping with Method

        @RequestMapping(value="/method")
        @ResponseBody
        public String method(){
            return "method";
        }
      
    • @RequestMapping with HTTP Method

        @RequestMapping(value="/method", method{RequestMethod.POST,RequestMethod.GET})
        @ResponseBody
        public String method(){
            return "method";
        }
      
    • @RequestMapping with Headers

        @RequestMapping(value="/method", headers="name=jack")
        @ResponseBody
        public String method(){
            return "method";
        }
      
  4. @PathVariable

    This annotation is used to extract the value from the URI. The @PathVariable annotation can be used to handle template variables in the request URI mapping and set them as method parameters. Spring MVC allows us to use multiple @PathVariable annotations in the same method. Let's understand it with an example

     @GetMapping("/api/employees/{id}")
     @ResponseBody
     public String getEmployeesById(@PathVariable String id) {
         return "ID: " + id;
     }
    

    Here @PathVariable annotation is used to extract the templated part of the URI, represented by the variable {id}.

     @GetMapping("/api/employees/{id}/{address}")
     @ResponseBody
     public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String address) {
         return "ID: " + id + ", address: " + address;
     }
    

    Here in this case we used multiple@PathVariable annotations in the same method. Also, this method has multiple parameters like id and address.

  5. @RequestParam

    This annotation is mainly used to retrieve the URL parameter and map it to the method argument. The @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the given method.

    Let's have a look at an example given below

     @GetMapping("/api/empl")
     @ResponseBody
     public String getEmlp(@RequestParam String id) {
         return "ID: " + id;
     }
    

    In this example, we used @RequestParam to extract the id query parameter.

    A simple GET request would invoke getEmpl.

  6. @ModelAttribute

    This annotation binds a method parameter or method return value to a named model attribute and then reveals it to a web view. @ModelAttribute can either be used as a method parameter or at the method level.

     @ModelAttribute
     public void addAttributes(Model model) {
         model.addAttribute("msg", "Welcome to India!");
     }
    

    In the example above we see a method that adds an attribute named msg to all models defined in the controller class.

    NOTE: @ModelAttribute methods are invoked before the controller methods annotated with @RequestMapping are invoked. This is because the model object has to be created before any processing starts inside the controller methods.

    Conclusion

    In this article, I have the most frequently used annotations and their uses along with examples.

    I am grateful for the time you have invested in reading this. I hope you enjoyed reading my article. Do like, share and comment your thoughts in the comment section below.

    References

    1. GeeksForGeeks

    2. Baeldung

Did you find this article valuable?

Support Ishita Ghosh by becoming a sponsor. Any amount is appreciated!