Which are the Spring MVC annotations you must know?

Which are the Spring MVC annotations you must know?

If you had come across the Spring framework, you most probably would've heard of annotations. Well, what are annotations in Java?

To begin with, let's go back to the time when XML configuration was used (before Spring 2.5v). It included writing XMLConfiguration, and then accessing beans from there, which looked like this

`


public class HelloSpringApp {

    public static void main(String[] args) {

        // Load the Spring Configuration File
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Retrieve bean from Spring Container
        // Alias(Bean - ID), Interface implemented by that class
        Coach bbCoach = context.getBean("baseballCoach", Coach.class);
    }
}

`

applicationContext.xml file is the one that creates a Spring container for all the beans.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Load the properties file -->
    <context:property-placeholder location = "classpath:sport.properties"/>
    <!--  Dependency Injection -->
    <bean id = "baseballCoach" class = "com.shivu.springOne.BaseballCoach">
        <constructor-arg ref = "myFortuneService"/>
    </bean>
</beans>

`

Well, how do you feel now? uncomfortable, right?

In the applicationContext.xml file, you can see that the first opening tag is <beans>. This is the factory that handles all the beans. Then, you can define each bean with <bean> with id, classpath, and passing reference for any constructor or interface implemented. This used to take a huge time to just get started with your project. From Spring 2.5 release, Annotations were introduced.

Annotations

Annotations are a form of metadata that provide data about a program that is not part of the program itself. They provide information for the compiler, software tools can process annotation information to generate code, XML files, and so forth.

Annotations have replaced XMLConfiguration in a lot of scenarios. In SpringMVC, many such annotations play a very important role in building an MVC application. We shall have a glance at some of them.

  1. @Controller

    This can be used with Spring MVC applications and WebFlux. This is a class-level annotation and acts as a stereotype for the annotated class. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping (coming up) annotations. It is used to detect the components in the classpath and autoregister the bean definitions. The request handler methods present in class with this annotation can serve templates.

  2. @RequestMapping

    This annotation is used to map URLs like /movies onto an entire class or a particular handler method. Typically the type-level annotation maps a specific request path (or path pattern) onto a form controller. This annotation takes a path and HTTP methods that can be used for narrowing the request handler. Moreover, it also takes in consumes, params, header, method, name, and path.

    This annotation can be used as follows :

    @RequestMapping("/index")

    @RequestMapping({"/", "/index", "/home"}) - multiple URLs to a single handler

    @RequestMapping("/index", method = RequestMapping.GET) - Only GET requests are served.

    In fact, we have the following RequestMapping annotations too.

    1. @GetMapping - Equivalent to @RequestMapping("/index", method = RequestMapping.GET) handles only get requests for this URL

    2. @PostMapping("/submit") handles only posts requests for this URL

    3. @PutMapping

    4. @PatchMapping

    5. @DeleteMapping

  1. @RequestBody

    This annotation maps the HttpRequest body to a transfer or domain object (form data to a Java object in the Project) enabling automatic deserialization.

  2. @ResponseBody

    This annotation is used to bind the method return value to the response body. This annotation simply tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

  3. @PathVariable

    This is used to extract values from the URL. This is most useful for building RESTful web services. This can be used with optional URL values also

    @RequestMapping("/employee/{id}")

    public String getEmployee(@PathVariable(required = false) String id){

    }

  4. @RequestParam

    Aka QueryParameter, this annotation is used to extract the query parameters in the URL. It is most suitable for developing web applications. It can define default values if the query parameter is not present in the URL.

    @RequestMapping("/movies")

    public String list_movies(@RequestParam(value = "limit", required = false) Integer limit) {

    }

  5. @RequestHeader

    This is used to get details about the HTTP request headers. It can be used as a method parameter. Optional elements include name, value, required and deafultValue.

    @GetMapping("/test1")

    public String getHeaders(@RequestHeader String authorization) {

    }

  6. @RestController

    This annotation is the combination of @Controller and @ResponseBody. The request handler methods present in class with this annotation can only serve data but not templates. Hence, this is widely used in REST API applications. If this is used, there is no need to annotate each method with @ResponseBody.

  7. @CrossOrigin

    This annotation is used both at the class & method levels. It is used to enable cross-origin requests. It is useful for cases if the host serving JavaScript is different from the data serving host. In such cases, the CORS ( Cross-Origin Resource Sharing) enables cross-domain communication. The default behavior of this annotation allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation, and maxAge=30min. However, we can control and customize the behavior.

  8. @RequestAttribute

    This is used to wrap a method parameter to the request attribute. It gives convenient access to the request attributes from a controller method.

    public String getHome(@RequestAttribute("home") String home) {
          //
      }
    

Here is a demonstration of most of the above annotations :)

@Controller
@CrossOrigin
publc class AdminController {

    @PostMapping("admin/categories/add")
    public String postCategoriesAdd(@ModelAttribute("category") Category       category){ 
        categoryService.addCategory(category);
        return "redirect:/admin/categories";
    }

    @GetMapping("admin/categories/delete/{id}")
    public String deleteCat(@PathVariable("id") int catId){
        categoryService.removeCategoryById(catId);
        return "redirect:/admin/categories";
    }

     @PostMapping("/admin/products/add")
    public String productAddPost(@ModelAttribute("ProductDTO") ProductDTO     productDTO, 
    @RequestParam("productImage")MultipartFile file,     @RequestParam("imgName")String imgName) throws IOException {
        Product product = new Product();
        product.setId(productDTO.getId());
        product.setName(productDTO.getName());
        product.setCategory(categoryService.getCategoryById(productDTO.getCategoryId()).get());
        product.setDescription(productDTO.getDescription());
        product.setPrice(productDTO.getPrice());
        return "redirect:/admin/products";
    }
}

Thank you for your time. Check out my other blogs too...

ย