Comprehensive Guide to Common Spring Framework Annotations
This article provides a comprehensive overview of the most commonly used Spring Framework annotations, including core, stereotype, Spring Boot, MVC/REST, data access, scheduling, and testing annotations, with explanations and code examples illustrating their usage in Java backend development.
Core Annotations
@Requiredmarks a bean setter as mandatory; if the property is not injected, a BeanInitializationException is thrown. @Autowired can be placed on fields, setters, or constructors to declare a dependency that Spring resolves by type.
Example of field injection:
@Component
public class User {
@Autowired
private Address address;
}Example of setter injection with custom code:
@Component
public class User {
private Address address;
@Autowired
public void setAddress(Address address) {
// custom code
this.address = address;
}
}Constructor injection (only one constructor may be annotated; after Spring 4.3 it is optional if there is a single constructor):
@Component
public class User {
private Address address;
public User(Address address) {
this.address = address;
}
} @Qualifierworks with @Autowired to disambiguate which bean should be injected when multiple candidates exist.
@Component
public class User {
@Autowired
@Qualifier("address1")
private Address address;
} @Configurationindicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions.
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
return new AdminUser();
}
} @ComponentScanis typically used together with @Configuration to specify the packages that Spring should scan for annotated components. @Lazy can be placed on a component class or on individual @Bean methods to defer bean instantiation until it is first needed. @Value injects property values or Spring Expression Language (SpEL) results into fields, constructor parameters, or method parameters.
Stereotype Annotations
@Componentdeclares a generic Spring-managed component. @Controller marks a class as a Spring MVC controller; it is a specialized form of @Component. @Service indicates that a class holds business logic; also a specialization of @Component. @Repository designates a DAO component, enabling exception translation for database access.
Spring Boot Annotations
@EnableAutoConfigurationtells Spring Boot to automatically configure beans based on the classpath. @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan for a Spring Boot entry point.
Spring MVC and REST Annotations
@RequestMappingmaps HTTP requests to handler classes or methods; method‑level variants such as @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping provide shortcut mappings for specific HTTP verbs.
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUserList() {
return "users";
}
} @CookieValuebinds a specific cookie value to a method parameter.
@RequestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie) {
// ...
} @CrossOriginenables 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, and @ControllerAdvice provide fine‑grained control over request handling, data binding, and exception processing.
Data Access Annotations
@Transactionalcan be placed on classes or methods to indicate that the execution should be wrapped in a transaction; the annotation itself is metadata consumed by transaction managers.
Task Execution and Scheduling Annotations
@Scheduledmarks a method for periodic execution. Fixed‑delay waits for the previous execution to finish; fixed‑rate does not.
@Scheduled(fixedDelay = 1000)
public void schedule() { }
@Scheduled(fixedRate = 1000)
public void scheduleG() { } @Asyncindicates that a method should run in a separate thread, optionally returning a Future.
Testing Annotations
@ContextConfigurationtogether with @RunWith(SpringJUnit4ClassRunner.class) loads a Spring context for integration tests.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest { }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.
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.
