Comprehensive Guide to Spring MVC Annotations and Their Usage
This article provides an in‑depth overview of Spring MVC annotations such as @Controller, @RequestMapping, @Autowired, @Resource, @ModelAttribute, @SessionAttributes, @PathVariable, and @RequestParam, explaining their purposes, configuration methods, attribute injection rules, and advanced usage with practical code examples.
In Spring MVC, a class annotated with @Controller becomes a controller that handles requests dispatched by DispatcherServlet. Methods are mapped to URLs using @RequestMapping (or its shortcut annotations) and can receive parameters via @PathVariable, @RequestParam, @RequestHeader, or @CookieValue.
The @Controller bean must be registered with Spring either by defining it as a
<bean class="com.host.app.web.controller.MyController"/>in the XML configuration (method 1) or by enabling component scanning with
<context:component-scan base-package="com.host.app.web"/>(method 2).
<!-- method 1 -->
<bean class="com.host.app.web.controller.MyController"/>
<!-- method 2 -->
<context:component-scan base-package="com.host.app.web"/>The @RequestMapping annotation can specify the request path, HTTP method, required parameters, headers, consumes/produces media types, and more. Example attributes include value, method, params, and headers:
@RequestMapping(value="/testParams", params={"param1=value1", "param2", "!param3"})
public String testParams() {
System.out.println("test Params...........");
return "testParams";
}Dependency injection can be performed with @Autowired (by type) or @Resource (by name or type). Both annotations can be placed on fields or setter methods. Example:
public class TestServiceImpl {
@Autowired
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}When using @Resource, the name attribute maps to the bean name, while type maps to the bean type. The injection order follows: both name and type specified → name only → type only → neither (by name fallback).
@Resource(name="userDao")
private UserDao userDao;
@Resource(name="userDao")
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}The @ModelAttribute annotation can be applied to methods to populate the model before any @RequestMapping method executes, or to method parameters to bind model attributes (or session attributes) to arguments. Combined with @SessionAttributes, selected model attributes are stored in the HTTP session.
@Controller
@SessionAttributes({"intValue", "stringValue"}, types={User.class})
public class MyController {
@ModelAttribute("hello")
public String getModel() { return "world"; }
@ModelAttribute("intValue")
public int getInteger() { return 10; }
@RequestMapping("sayHello")
public void sayHello(@ModelAttribute("hello") String hello,
@ModelAttribute("intValue") int num,
@ModelAttribute("user2") User user,
Writer writer) throws IOException {
writer.write("Hello " + hello + ", Hello " + user.getUsername() + num);
}
} @PathVariableextracts values from URI templates, while @RequestParam retrieves query‑string or form‑encoded parameters. Example of using both:
@RequestMapping(value="/user/{userId}/roles/{roleId}", method=RequestMethod.GET)
public String getLogin(@PathVariable("userId") String userId,
@PathVariable("roleId") String roleId) {
System.out.println("User Id : " + userId);
System.out.println("Role Id : " + roleId);
return "hello";
}
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}Additional annotations such as @ResponseBody (to write the return value directly to the response body), @RequestHeader, @CookieValue, and @RequestBody (for JSON/XML payloads) are also covered, illustrating how Spring MVC supports a wide range of request handling scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
