Comprehensive Guide to Common Spring Framework Annotations
This article provides a detailed overview of the most frequently used Spring annotations—including core, MVC/REST, Boot, stereotype, data access, scheduling, and testing annotations—explaining their purposes, usage rules, and providing Java code examples for each.
Since Java 5 introduced annotations and Spring 2.5 began moving away from XML configuration, Spring now relies heavily on annotations to define beans, inject dependencies, and configure the framework.
Core Annotations
@Required marks a bean property as mandatory; missing injection throws BeanInitializationException .
@Autowired can be placed on fields, setters, or constructors to inject dependencies by type. When used on a field, Spring automatically assigns the bean, even on private fields (though not recommended).
@Component
public class User {
@Autowired
private Address address;
}When @Autowired is applied to a setter, custom logic can be added inside the method.
@Component
public class User {
private Address address;
@Autowired
public void setAddress(Address address) {
// custom code
this.address = address;
}
}For constructor injection, only one constructor may be annotated. Since Spring 4.3, if a class has a single constructor, the annotation can be omitted.
@Component
public class User {
private Address address;
@Autowired
public User(Address address) {
this.address = address;
}
}@Qualifier works with @Autowired to disambiguate beans when multiple candidates of the same type exist.
@Component
public class User {
@Autowired
@Qualifier("address1")
private Address address;
}@Configuration marks a class as a source of bean definitions, similar to an XML configuration file. Methods inside can be annotated with @Bean to create beans.
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
AdminUser adminUser = new AdminUser();
return adminUser;
}
}@ComponentScan is usually used together with @Configuration to specify the packages that Spring should scan for annotated components.
@Lazy delays bean initialization until the bean is first requested.
@Value injects property values using Spring Expression Language ( #{} ) or placeholders ( ${} ) into fields, constructor parameters, or method parameters.
Spring MVC and REST Annotations
@Controller declares a class as a Spring MVC controller (a specialized @Component ).
@RequestMapping maps HTTP requests to controller classes or methods. It can specify the HTTP method via the method attribute.
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUserList() {
return "users";
}
}Since Spring 4.3, shortcut annotations such as @GetMapping , @PostMapping , @PutMapping , @PatchMapping , and @DeleteMapping provide more concise mappings.
@CookieValue binds a specific cookie value to a method parameter.
@RequestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie) {
// cookie contains the JSESSIONID value
}@CrossOrigin enables CORS support on a controller or method.
@RestController
@CrossOrigin(origins = "http://xx.com")
@RequestMapping("/users")
public class AccountController {
@GetMapping("/login")
public Result userLogin() {
// ...
}
}@ExceptionHandler defines a method to handle specific exceptions.
@InitBinder customizes the WebDataBinder for request parameter binding.
@MatrixVariable extracts matrix‑style parameters from URLs; it requires enabling matrix variables in MVC configuration.
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42, q == 11
}To enable matrix variables:
<mvc:annotation-driven enable-matrix-variables="true"/>and configure the UrlPathHelper to retain semicolon content.
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}@PathVariable binds URI template variables to method parameters, while @RequestAttribute binds request attributes.
@RequestBody maps the HTTP request body to a method argument using HttpMessageConverter .
@RequestHeader binds HTTP header values to method parameters.
@RequestParam binds query parameters or form data to method arguments.
@RequestPart handles multipart file uploads.
@ResponseBody indicates that the return value of a method should be written directly to the HTTP response body.
@ResponseStatus sets the HTTP status code for a method or exception class.
@ControllerAdvice and @RestControllerAdvice provide global exception handling, data binding, and model attribute configuration across all controllers.
Stereotype Annotations
@Component declares a generic Spring bean.
@Service marks a class as a service layer component.
@Repository indicates a DAO component and enables exception translation.
Data Access Annotation
@Transactional declares transactional boundaries on classes or methods; the actual transaction management is performed by Spring infrastructure.
Task Execution and Scheduling Annotations
@Scheduled schedules a method for periodic execution. fixedDelay waits for the previous execution to finish, while fixedRate triggers at a fixed interval regardless of execution time.
@Scheduled(fixedDelay = 1000)
public void schedule() { }
@Scheduled(fixedRate = 1000)
public void scheduleFixedRate() { }@Async runs a method asynchronously in a separate thread; the return type can be void or a Future .
Testing Annotations
@ContextConfiguration specifies the configuration files or classes to load for Spring integration tests, typically used with @RunWith(SpringJUnit4ClassRunner.class) .
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest { }Overall, the article enumerates and explains the most common Spring annotations, providing concise descriptions and practical code snippets to help developers adopt annotation‑driven configuration in modern Java backend development.
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.