Mastering Spring Web MVC Annotations: A Complete Guide
This article provides a comprehensive overview of Spring Web MVC and Spring Boot annotations—including @RequestMapping, its attribute set, shortcut mapping annotations, controller advice, dependency injection, bean scopes, conditional configuration, and related component stereotypes—illustrated with code snippets and diagrams for Java backend developers.
Spring Web MVC Annotations
@RequestMapping
@RequestMappingmaps web requests to handler methods. Spring MVC and Spring WebFlux support it via RequestMappingHandlerMapping and RequestMappingHandlerAdapter.
The annotation can be placed on classes or methods and has six attributes: value: the request URL or its alias. method: HTTP method name. params: filter requests based on HTTP parameters. header: filter requests based on HTTP headers. consume: allowed media types in the request body. produces: media types produced in the response body.
Before using @RequestMapping, the handler class must be annotated with @Controller or @RestController.
Example usage of @RequestMapping on a class and method:
@RequestBody
@RequestBodybinds the request body to a method parameter using HttpMessageConverter. It can be combined with @Valid for validation.
@GetMapping
@GetMappinghandles HTTP GET requests and is a shortcut for @RequestMapping(method=RequestMethod.GET).
@PostMapping
@PostMappinghandles HTTP POST requests and is a shortcut for @RequestMapping(method=HttpMethod.POST).
@PutMapping
@PutMappinghandles HTTP PUT requests and is a shortcut for @RequestMapping(method=HttpMethod.PUT).
@DeleteMapping
@DeleteMappinghandles HTTP DELETE requests and is a shortcut for @RequestMapping(method=HttpMethod.DELETE).
@PatchMapping
@PatchMappinghandles HTTP PATCH requests and is a shortcut for @RequestMapping(method=HttpMethod.PATCH).
@ControllerAdvice
@ControllerAdviceis a specialization of @Component that works with @ExceptionHandler, @InitBinder, and @ModelAttribute to handle exceptions and bind data globally.
@ResponseBody
@ResponseBodywrites the return value of a controller method directly to the HTTP response. When used on a class annotated with @RestController, it is implicit.
@ExceptionHandler
@ExceptionHandlermarks a method to handle specific exception types thrown by controller methods.
@ResponseStatus
@ResponseStatussets the HTTP status code for a handler method.
@PathVariable
@PathVariablebinds a method parameter to a URI template variable defined in @RequestMapping. It supports value or name as an alias.
@RequestParam
@RequestParambinds a method parameter to a request parameter, with optional defaultValue and required settings.
@Controller
@Controllermarks a class as a Spring MVC controller (a specialization of @Component).
@RestController
@RestControllercombines @Controller and @ResponseBody, eliminating the need to annotate each method with @ResponseBody.
@ModelAttribute
@ModelAttributeaccesses existing model attributes or adds new ones; when placed on a method, its return value is added to the model before the handler executes.
@CrossOrigin
@CrossOriginenables CORS support for a controller or method, allowing fine‑grained cross‑origin configuration.
@InitBinder
@InitBindercustomizes data binding for request parameters, such as date formatting.
@ComponentScan
@ComponentScanconfigures the packages to be scanned for components, using basePackages or value.
@Component
@Componentmarks a generic bean for Spring container management.
@Service
@Serviceis a specialization of @Component for business‑logic services.
@Repository
@Repositorymarks DAO classes for persistence and exception translation.
@DependsOn
@DependsOnforces bean initialization order.
@Bean
@Beandeclares a method that returns a Spring‑managed bean; attributes initMethod and destroyMethod define lifecycle callbacks.
@Scope
@Scopedefines bean scope such as singleton, prototype, request, session, etc.
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)@Autowired
@Autowiredinjects dependencies into constructors, fields, or setter methods.
@Primary
@Primarydesignates a bean as the default when multiple candidates of the same type exist.
Conditional Annotations
@ConditionalOnClassand @ConditionalOnMissingClass enable configuration based on class presence.
@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoConfiguration { } @ConditionalOnBeanand @ConditionalOnMissingBean act on bean existence.
@Bean
@ConditionalOnBean(name="dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() { }
@Bean
@ConditionalOnMissingBean
public MyBean myBean() { } @ConditionalOnPropertychecks configuration properties.
@Bean
@ConditionalOnProperty(name="alipay", havingValue="on")
Alipay alipay() { return new Alipay(); } @ConditionalOnResourceactivates when a resource exists.
@ConditionalOnResource(resources="classpath:website.properties")
Properties addWebsiteProperties() { } @ConditionalOnWebApplicationand @ConditionalOnNotWebApplication detect web environment.
@ConditionalOnWebApplication
HealthCheckController healthCheckController() { } @ConditionalExpressionevaluates a SpEL expression to decide bean creation.
@Bean
@ConditionalException("${localstore} && ${local == 'true'}")
LocalFileStore store() { } @Conditionalallows custom condition classes.
@Conditional(CustomConditional.class)
CustomProperties addCustomProperties() { }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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
