Master Spring Annotations: From @RequestMapping to Conditional Configuration
This comprehensive guide explains the purpose, attributes, and usage of Spring MVC, DI, and conditional annotations—including @RequestMapping, @GetMapping, @Autowired, @Scope, @ConditionalOnClass, and more—providing clear examples and code snippets for each.
Hello, I am your friend Architect Jun, a poet‑architect who also writes code.
Table of Contents
Spring Web MVC and Spring Bean Annotations
Spring Bean Annotations
Spring Dependency Injection Annotations
Scope Annotations
@Autowired
@Primary
@PostConstruct and @PreDestroy
@Qualifier
@SpringBootApplication and Conditional Annotations
Spring Web MVC Annotations
@RequestMapping maps web requests to handler methods. It is supported by
RequestMappingHandlerMappingand
RequestMappingHandlerAdapter. The annotation has six attributes:
value: the 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: allowed media types in the response body
Before using
@RequestMapping, the class must be annotated with
@Controlleror
@RestController.
Example 1:
Class‑level
@RequestMappingconcatenates its
valuewith method‑level mappings.
@RequestBody
@RequestBodybinds the request body to an object using
HttpMessageConverter. Validation can be added with
@Valid.
@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
@ControllerAdviceextends
@Componentand works with
@ExceptionHandler,
@InitBinder, and
@ModelAttributeto handle exceptions globally.
@ResponseBody
@ResponseBodywrites the method return value directly to the HTTP response. It is implicit in
@RestController.
@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. It supports
valueor
nameas an alias.
@RequestParam
@RequestParambinds a method parameter to a web request parameter, with optional
defaultValue.
@Controller
@Controlleris a specialization of
@Componentfor Spring MVC controllers.
@RestController
@RestControllercombines
@Controllerand
@ResponseBody, eliminating the need for the latter on each method.
@ModelAttribute
@ModelAttributeadds an attribute to the model or binds a method’s return value to the model.
@CrossOrigin
@CrossOriginenables CORS support for a controller or method.
@InitBinder
@InitBindercustomizes data binding for web request parameters, such as date formatting.
Spring Bean Annotations
@ComponentScanconfigures packages to scan for components.
@Componentmarks a generic component class for Spring management.
@Serviceis a specialization of
@Componentfor business logic.
@Repositorymarks DAO classes for persistence.
Spring DI Annotations
@DependsOnforces bean initialization order.
@Beandeclares a bean method; its
initMethodand
destroyMethodcontrol lifecycle callbacks.
Scope Annotations
@Scopedefines bean scope such as
singleton,
prototype,
request,
session, etc.
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)Examples of singleton and prototype scopes are illustrated with images.
@Autowired
@Autowiredinjects dependencies into constructors, setters, or fields.
@Primary
@Primarygives higher priority to a bean when multiple candidates of the same type exist.
@PostConstruct and @PreDestroy
These JSR‑250 annotations define methods to run after bean initialization and before bean destruction.
@Qualifier
@Qualifierdisambiguates which bean should be injected when multiple candidates exist.
@SpringBootApplication and Conditional Annotations
@SpringBootApplicationcombines
@Configuration,
@EnableAutoConfiguration, and
@ComponentScan.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Conditional annotations such as
@ConditionalOnClass,
@ConditionalOnMissingBean,
@ConditionalOnProperty, and
@Conditionalenable bean creation based on classpath, bean presence, property values, or custom conditions.
@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(); }Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
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.