Commonly Used Spring Framework Annotations Explained
This article provides a comprehensive overview of the most frequently used Spring and Spring Boot annotations, explaining their purposes, usage scenarios, and includes practical Java code examples for core, MVC/REST, stereotype, data access, scheduling, asynchronous, and testing annotations.
Spring has gradually moved from XML configuration to annotation‑based configuration since Java 5 introduced annotations and Spring 2.5 started to favor them.
1. Core Annotations
@Required – placed on a bean setter to indicate the property must be injected, otherwise a BeanInitializationException is thrown.
@Autowired – used on fields, setters, or constructors to declare a dependency that Spring will inject by type.
@Component
public class User {
@Autowired
private Address address;
}When used on a constructor, only one constructor may be annotated; from Spring 4.3 a single constructor is automatically autowired even without the annotation.
@Component
public class User {
private Address address;
public User(Address address) {
this.address = address;
}
}@Qualifier – works with @Autowired to disambiguate which bean to inject when multiple candidates 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.
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
AdminUser adminUser = new AdminUser();
return adminUser;
}
}@ComponentScan – used together with @Configuration to specify the packages that Spring should scan for annotated components.
@Lazy – indicates that a bean (or all @Bean methods within a @Configuration class) should be lazily initialized, i.e., created only when first needed.
@Value – injects property values using Spring Expression Language (#{}) or placeholder syntax (${}) into fields, constructor parameters, or method parameters.
2. Spring MVC and REST Annotations
@Controller – declares a class as a Spring MVC controller (a specialized @Component).
@RequestMapping – maps HTTP requests to handler classes or methods; can specify path, HTTP method, and other attributes.
@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 method‑specific mappings.
@CookieValue – binds a specific cookie value to a method parameter.
@RequestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie) {
// ...
}@CrossOrigin – enables CORS support on a controller or method.
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
@CrossOrigin(origins = "http://xx.com")
@RequestMapping("/login")
public Result userLogin() {
// ...
}
}@ExceptionHandler , @InitBinder , @MatrixVariable , @PathVariable , @RequestAttribute , @RequestBody , @RequestHeader , @RequestParam , @RequestPart , @ResponseBody , @ResponseStatus , @ControllerAdvice , @RestController , and @RestControllerAdvice – various annotations that control exception handling, data binding, URL matrix variables, request attribute binding, request body conversion, header/parameter extraction, response handling, and global controller advice.
Matrix variables require enabling via <mvc:annotation-driven enable-matrix-variables="true"/> or Java configuration that disables semicolon removal.
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}3. Spring Boot Annotations
@EnableAutoConfiguration – placed on the main application class to trigger Spring Boot’s auto‑configuration mechanism.
@SpringBootApplication – combines @Configuration, @EnableAutoConfiguration, and @ComponentScan for a Spring Boot entry point.
4. Stereotype Annotations
@Component , @Service , @Repository – specialized @Component variants that indicate the role of a bean (generic component, service layer, or data access layer) and may trigger additional behavior such as exception translation for @Repository.
5. Data Access Annotation
@Transactional – marks a class or method as transactional; the actual transaction management is provided by Spring’s infrastructure.
6. 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 scheduleRate() { }@Async – runs a method asynchronously in a separate thread; the method may return a Future.
7. Test Annotations
@ContextConfiguration – used on test classes to specify configuration classes or XML files for the Spring test context, typically together with @RunWith(SpringJUnit4ClassRunner.class) .
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest { }Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn 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.