Master Spring MVC & DI Annotations: From @RequestMapping to @Conditional
This comprehensive guide explains the purpose, configuration attributes, and practical usage of Spring MVC request‑mapping annotations, Spring dependency‑injection annotations, scope settings, and conditional annotations, providing code snippets and visual examples for each feature.
Spring Web MVC Annotations
The @RequestMapping annotation maps HTTP requests to handler methods. Spring MVC and Spring WebFlux support it via RequestMappingHandlerMapping and RequestMappingHandlerAdapter. It can be placed on classes or methods and requires the class to be annotated with @Controller or @RestController. value: the URL pattern or alias. method: HTTP method(s) to match. params: filter requests based on presence, default, or value of query parameters. header: filter requests based on HTTP header conditions. consume: media types that the request body can consume. produces: media types that the response can produce.
Example usage of @RequestMapping (image omitted for brevity).
When placed on a class, the class‑level value is prefixed to method‑level mappings.
@RequestBody binds the request body to a method parameter using an HttpMessageConverter. Validation can be added with @Valid.
@GetMapping is a shortcut for @RequestMapping(method=RequestMethod.GET).
@PostMapping is a shortcut for @RequestMapping(method=HttpMethod.POST).
@PutMapping is a shortcut for @RequestMapping(method=HttpMethod.PUT).
@DeleteMapping is a shortcut for @RequestMapping(method=HttpMethod.DELETE).
@PatchMapping is a shortcut for @RequestMapping(method=HttpMethod.PATCH).
@ControllerAdvice works with @ExceptionHandler, @InitBinder, and @ModelAttribute to provide global exception handling and data binding.
@ResponseBody writes the method return value directly to the HTTP response. When used on a class annotated with @RestController, the annotation is implicit.
@ExceptionHandler marks a method to handle specific exception types thrown by controller methods.
@ResponseStatus sets the HTTP status code for a handler method.
@PathVariable binds a method parameter to a URI template variable. The value or name attribute can provide an alias; require=false makes the variable optional.
@RequestParam binds a method parameter to a query parameter. It supports default values and required flags.
@Controller marks a class as a Spring MVC controller (a specialization of @Component).
@RestController combines @Controller and @ResponseBody, eliminating the need to annotate each method with @ResponseBody.
@ModelAttribute adds attributes to the model before a view is rendered. When placed on a method, its return value is added to the model.
@CrossOrigin enables CORS support for a controller or method, allowing fine‑grained cross‑origin configuration.
@InitBinder customizes data binding for web request parameters, such as date formatting.
Spring Dependency Injection (DI) Annotations
@DependsOn forces the initialization order of beans.
@Bean declares a bean method. The attributes initMethod and destroyMethod specify lifecycle callbacks.
@Scope defines bean scope. Common scopes include singleton, prototype, request, session, and globalSession. Example for prototype scope:
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)@Autowired injects dependencies. It can be applied to constructors, setter methods, or fields.
@Primary designates a bean as the default candidate when multiple beans of the same type exist.
@PostConstruct and @PreDestroy (from JSR‑250) define methods to run after bean creation and before bean destruction.
@Qualifier resolves ambiguity when multiple beans of the same type are present.
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. A typical main class looks like:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}@EnableAutoConfiguration tells Spring to configure beans based on classpath dependencies.
Conditional annotations allow bean registration based on environment conditions: @ConditionalOnClass /
@ConditionalOnMissingClass @ConditionalOnBean/
@ConditionalOnMissingBean @ConditionalOnProperty @ConditionalOnResource @ConditionalOnWebApplication/
@ConditionalOnNotWebApplication @ConditionalExpression @Conditional(custom conditions)
Examples:
@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoConfiguration { /* ... */ } @Bean
@ConditionalOnBean(name="dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() { /* ... */ } @Bean
@ConditionalOnMissingBean
public MyBean myBean() { return new MyBean(); } @Bean
@ConditionalOnProperty(name="alipay", havingValue="on")
Alipay alipay() { return new Alipay(); } @ConditionalOnResource(resources="classpath:website.properties")
Properties addWebsiteProperties() { /* ... */ } @ConditionalOnWebApplication
HealthCheckController healthCheckController() { /* ... */ } @Bean
@ConditionalExpression("${localstore} && ${local == 'true'}")
LocalFileStore store() { /* ... */ }These annotations give developers fine‑grained control over bean creation based on the presence of classes, beans, properties, resources, or custom expressions.
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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
