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.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Mastering Spring Web MVC Annotations: A Complete Guide

Spring Web MVC Annotations

@RequestMapping

@RequestMapping

maps 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

@RequestBody

binds the request body to a method parameter using HttpMessageConverter. It can be combined with @Valid for validation.

@GetMapping

@GetMapping

handles HTTP GET requests and is a shortcut for @RequestMapping(method=RequestMethod.GET).

@PostMapping

@PostMapping

handles HTTP POST requests and is a shortcut for @RequestMapping(method=HttpMethod.POST).

@PutMapping

@PutMapping

handles HTTP PUT requests and is a shortcut for @RequestMapping(method=HttpMethod.PUT).

@DeleteMapping

@DeleteMapping

handles HTTP DELETE requests and is a shortcut for @RequestMapping(method=HttpMethod.DELETE).

@PatchMapping

@PatchMapping

handles HTTP PATCH requests and is a shortcut for @RequestMapping(method=HttpMethod.PATCH).

@ControllerAdvice

@ControllerAdvice

is a specialization of @Component that works with @ExceptionHandler, @InitBinder, and @ModelAttribute to handle exceptions and bind data globally.

@ResponseBody

@ResponseBody

writes the return value of a controller method directly to the HTTP response. When used on a class annotated with @RestController, it is implicit.

@ExceptionHandler

@ExceptionHandler

marks a method to handle specific exception types thrown by controller methods.

@ResponseStatus

@ResponseStatus

sets the HTTP status code for a handler method.

@PathVariable

@PathVariable

binds a method parameter to a URI template variable defined in @RequestMapping. It supports value or name as an alias.

@RequestParam

@RequestParam

binds a method parameter to a request parameter, with optional defaultValue and required settings.

@Controller

@Controller

marks a class as a Spring MVC controller (a specialization of @Component).

@RestController

@RestController

combines @Controller and @ResponseBody, eliminating the need to annotate each method with @ResponseBody.

@ModelAttribute

@ModelAttribute

accesses 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

@CrossOrigin

enables CORS support for a controller or method, allowing fine‑grained cross‑origin configuration.

@InitBinder

@InitBinder

customizes data binding for request parameters, such as date formatting.

@ComponentScan

@ComponentScan

configures the packages to be scanned for components, using basePackages or value.

@Component

@Component

marks a generic bean for Spring container management.

@Service

@Service

is a specialization of @Component for business‑logic services.

@Repository

@Repository

marks DAO classes for persistence and exception translation.

@DependsOn

@DependsOn

forces bean initialization order.

@Bean

@Bean

declares a method that returns a Spring‑managed bean; attributes initMethod and destroyMethod define lifecycle callbacks.

@Scope

@Scope

defines bean scope such as singleton, prototype, request, session, etc.

@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)

@Autowired

@Autowired

injects dependencies into constructors, fields, or setter methods.

@Primary

@Primary

designates a bean as the default when multiple candidates of the same type exist.

Conditional Annotations

@ConditionalOnClass

and @ConditionalOnMissingClass enable configuration based on class presence.

@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoConfiguration { }
@ConditionalOnBean

and @ConditionalOnMissingBean act on bean existence.

@Bean
@ConditionalOnBean(name="dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() { }

@Bean
@ConditionalOnMissingBean
public MyBean myBean() { }
@ConditionalOnProperty

checks configuration properties.

@Bean
@ConditionalOnProperty(name="alipay", havingValue="on")
Alipay alipay() { return new Alipay(); }
@ConditionalOnResource

activates when a resource exists.

@ConditionalOnResource(resources="classpath:website.properties")
Properties addWebsiteProperties() { }
@ConditionalOnWebApplication

and @ConditionalOnNotWebApplication detect web environment.

@ConditionalOnWebApplication
HealthCheckController healthCheckController() { }
@ConditionalExpression

evaluates a SpEL expression to decide bean creation.

@Bean
@ConditionalException("${localstore} && ${local == 'true'}")
LocalFileStore store() { }
@Conditional

allows custom condition classes.

@Conditional(CustomConditional.class)
CustomProperties addCustomProperties() { }
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentSpring BootSpring MVCJava Annotations
Su San Talks Tech
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.