Commonly Used Spring Annotations – Core, MVC/REST, Boot, Stereotype, Transaction, Scheduling and Testing
This article provides a comprehensive overview of the most frequently used Spring annotations, covering core dependency‑injection annotations, MVC/REST mapping, Spring Boot configuration, stereotype components, transaction management, task scheduling, asynchronous execution, and testing support, with clear code examples for each.
Since Java 5 introduced annotations, the Spring framework has gradually moved from XML configuration to annotation‑based configuration. This guide summarises the most useful Spring annotations, grouped by their purpose.
1. Core Annotations
@Required Applied to a bean's setter method to indicate that the property must be injected; otherwise a BeanInitializationException is thrown.
@Autowired Used on fields, setter methods, or constructors to declare a dependency that Spring should inject by type.
@Component
public class User {
@Autowired
private Address address;
}The annotation can also be placed on a setter to add custom logic:
@Component
public class User {
private Address address;
@Autowired
public void setAddress(Address address) {
// custom code
this.address = address;
}
}When used on a constructor, only one constructor in a class may be annotated. From Spring 4.3 onward, a single‑constructor class is autowired automatically even without the annotation.
@Qualifier Combined with @Autowired to disambiguate which bean should be injected 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, equivalent to an XML configuration file. Methods annotated with @Bean inside the class define individual beans.
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
return new AdminUser();
}
}@ComponentScan 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 values from property files, environment variables, or Spring Expression Language (SpEL) into fields, constructor parameters, or method parameters.
2. Spring MVC and REST Annotations
@Controller and @RestController declare a class as a web controller; the latter combines @Controller and @ResponseBody.
@RequestMapping maps HTTP requests to handler classes or methods. Method‑level attributes such as method = RequestMethod.GET restrict the HTTP verb.
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUserList() {
return "users";
}
}Since Spring 4.3, shortcut annotations like @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping provide concise method mappings.
Other parameter‑binding annotations include @PathVariable, @RequestParam, @RequestBody, @RequestHeader, @CookieValue, @MatrixVariable (requires enabling matrix variables), @RequestAttribute, @SessionAttribute, and @ModelAttribute.
3. Spring Boot Annotations
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan, enabling auto‑configuration and component scanning for the application’s base package.
4. Stereotype Annotations
@Component – generic Spring component. @Service – business‑logic component. @Repository – data‑access component with automatic exception translation.
5. Data Access Annotation
@Transactional marks a class or method as participating in a transaction; the actual transaction handling is performed 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 does not.
@Scheduled(fixedDelay = 1000)
public void schedule() {
// task logic
}
@Scheduled(fixedRate = 1000)
public void scheduleFixedRate() {
// task logic
}@Async runs a method asynchronously in a separate thread; the return type can be void or a Future.
7. Testing Annotations
@ContextConfiguration specifies the configuration classes or XML files for a Spring test context, usually used together with @RunWith(SpringJUnit4ClassRunner.class).
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {
// test methods
}The article also includes promotional sections for free Alibaba Cloud server offers and references to a 7701‑page interview question PDF covering a wide range of technologies.
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.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
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.
