Commonly Used Spring Framework Annotations Overview
This article introduces the most frequently used Spring framework annotations—including core, MVC/REST, Spring Boot, stereotype, transaction, scheduling, and testing annotations—explaining their purposes, usage locations, and providing Java code examples to illustrate how they configure beans, handle requests, and manage application behavior.
Since Java 5 introduced annotations and Spring has gradually moved from XML configuration to annotation‑based configuration since version 2.5, this article summarizes the most commonly used Spring annotations and shows how they are applied in real code.
1. Core Annotations
@Required – placed on a bean setter to indicate that the property must be injected; otherwise a BeanInitializationException is thrown.
@Autowired – can be used on fields, setters or constructors to inject dependencies by type. Example:
@Component
public class User {
@Autowired
private Address address;
}When used on a setter, custom logic can be added:
@Component
public class User {
private Address address;
@Autowired
public void setAddress(Address address) {
// custom code
this.address = address;
}
}Only one constructor in a class may be annotated with @Autowired . Since Spring 4.3, if a class has a single constructor, the annotation can be omitted.
@Qualifier – works together 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 produce beans.
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
return new AdminUser();
}
}@ComponentScan – usually used together with @Configuration to specify the packages that Spring should scan for annotated components.
@Lazy – indicates that a bean (or all beans defined by a @Configuration class) should be instantiated only when first needed.
@Value – injects literal values or expressions (e.g., ${property} or #{SpEL}) 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. It can define a base URL at the class level and specific URLs at the method level.
@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 are available.
@CookieValue – binds a specific HTTP cookie to a method parameter.
@RequestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie) {
// use the cookie value
}@CrossOrigin – enables CORS support on a controller or method.
@RestController
@CrossOrigin(origins = "http://xx.com")
@RequestMapping("/users")
public class AccountController {
@RequestMapping("/login")
public Result userLogin() {
// ...
}
}Other request‑handling annotations include @ExceptionHandler , @InitBinder , @MatrixVariable (requires enabling), @PathVariable , @RequestBody , @RequestHeader , @RequestParam , @RequestPart , @ResponseBody , @ResponseStatus , @ControllerAdvice , @RestController , @RestControllerAdvice , @SessionAttribute and @SessionAttributes . Each of these controls a specific aspect of request processing or response generation.
3. Spring Boot Annotations
@EnableAutoConfiguration – placed on the main application class to trigger Spring Boot’s auto‑configuration mechanism.
@SpringBootApplication – a convenience annotation that combines @Configuration , @EnableAutoConfiguration and @ComponentScan . It should be placed on the primary source class of a Spring Boot project.
4. Stereotype Annotations
@Component – generic stereotype for any Spring‑managed component.
@Service – indicates a service‑layer bean; a specialized @Component .
@Repository – marks a data‑access component (DAO). It also enables exception translation for persistence‑related exceptions.
5. Data‑Access Annotation
@Transactional – can be applied to classes or methods to declare that they should be executed within a transaction. The annotation itself is metadata consumed by Spring’s transaction infrastructure.
6. Scheduling and Async Annotations
@Scheduled – schedules a method to be invoked periodically. Example of fixed‑delay and fixed‑rate scheduling:
@Scheduled(fixedDelay = 1000)
public void schedule() {
// task executed after previous execution finishes
}
@Scheduled(fixedRate = 1000)
public void scheduleRate() {
// task executed at a regular interval regardless of previous execution
}@Async – indicates that a method should run in a separate thread. The method may return void or a Future ‑compatible type.
7. Testing Annotations
@ContextConfiguration – used on test classes to specify the configuration classes or XML files that should be loaded for the test context. It is typically combined with @RunWith(SpringJUnit4ClassRunner.class) .
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {
// test methods
}The article concludes with a reference to a large collection of interview questions covering Java, Spring, databases, messaging, and many other 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.
