Spring Web MVC Useful Annotations

Spring has several annotations which perform different functionalities.
Some of them are as following.

@Component

@Component serves as a generic stereotype for any Spring-managed component.

@Repository

@Repository indicates DAO component in the persistence layer.

@Service

It indicates a Service component in the business layer.

@Component at Persistent Layer

package com.startwithjava.dao;
import org.springframework.stereotype.Component;

@Component
public class UserDAO 
{
	@Override
	public int save(User user) {
	 //do the code for saving the user
	}	
}

@Component at Service Layer

package com.startwithjava.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.startwithjava.UserDAO;

@Component
public class UserService 
{
	@Autowired
	UserDAO userDAO;

	@Override
	public void saveUser(User user) {
           userDAO.save(user);
	}
}

@Controller

The @Controller is used to annotate the class to mark it as Spring MVC controller stereotype.

@RequestMapping

@RequestMapping annotation can be used to map URLs such as /hello onto an entire class or a particular handler method.RequestMethod.GET and RequestMethod.POST are used for GET and POST request respectively.

HelloController.java

package com.startwithjava.controllers;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloController{
 
	@RequestMapping(value="/test",method = RequestMethod.GET)
	public String hello(){
		
           return "hello";
	}
}

@RequestBody

@RequestBody annotates parameters for access to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters.

@RequestMapping(path = "/save", method = RequestMethod.PUT)
public void savePost(@RequestBody String body, Writer writer) throws IOException {
    writer.write(body);
}

@ResponseBody

This annotation indicates that a method return value should be bound to the web response body.This annotation can be used to generate response through handler method without any view resolver.We can use this annotation to generate text,json,xml,pdf,xls,doc etc.

@RequestMapping(path = "/hello", method = RequestMethod.GET)
@ResponseBody
public String hello() {
    return "Hello World";
}

@ModelAttribute

Main objective of this annotation to bind the request parameters or form fields to an model object. This annotation can be used as the method arguments or before the method declaration.
Here is the example of user register after form submission form fields are injected to to User bean and processed.

RegisterController.java

package com.startwithjava.controllers;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/register")
public class RegisterController{
 
	@RequestMapping(method = RequestMethod.POST)
	public String register(@ModelAttribute User user){
	   System.out.println("First Name"+user.getFirstName());	
 System.out.println("Last Name"+user.getLastName());	
           return "success";
	}
}

@PathVariable

This annotation indicates that a method parameter should be bound to a URI template variable. Suppose if we need to fetch order detail by below url.
http://www.expertwebindia/order/10

@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public Order getOrder(@PathVariable int orderId){
//fetch order
}

Configuration for Component-scan

<?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-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
               
     <context:component-scan base-package="com.startwithjava"/>
     
</beans>

Leave a Reply