Commonly Used Spring Framework Annotations and Their Usage
This article introduces the most commonly used Spring framework annotations—including core, MVC/REST, Boot, stereotype, data access, scheduling, and testing annotations—explains their purposes, usage scenarios, and provides Java code examples illustrating how to apply them in typical Spring applications.
Spring introduced annotation support starting from Java 5, and since Spring 2.5 the framework has gradually moved away from XML configuration toward annotation‑based configuration.
Core Annotations
@Required is placed on a bean's setter to indicate that the property must be injected, otherwise a BeanInitializationException is thrown.
@Autowired can be used on fields, setters, or constructors to declare a dependency that Spring should inject by type. Example of field injection:
@Component
public class User {
@Autowired
private Address address;
}Setter injection allows custom logic:
@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; from Spring 4.3 it is optional when there is a single constructor):
@Component
public class User {
private Address address;
@Autowired
public User(Address address) {
this.address = address;
}
}@Qualifier works together with @Autowired to disambiguate beans of the same type:
@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 annotated with @Bean define individual beans:
@Configuration
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
AdminUser adminUser = new AdminUser();
return adminUser;
}
}@ComponentScan is usually paired with @Configuration to specify the packages that Spring should scan for annotated components.
@Lazy can be placed on a component or on a @Configuration class to defer bean initialization until the bean is first needed.
@Value injects property values using Spring Expression Language (SpEL) or placeholder syntax (${…}) into fields, constructor parameters, or method parameters.
Spring MVC and REST Annotations
@Controller marks 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 or HTTP methods at the method level. Example:
@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 replace @RequestMapping for the corresponding HTTP methods.
@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() {
// ...
}
}Exception handling, data binding, and model attributes are managed with @ExceptionHandler , @InitBinder , @ModelAttribute , @RequestAttribute , @RequestBody , @RequestHeader , @RequestParam , @RequestPart , @ResponseBody , @ResponseStatus , @ControllerAdvice , @RestController , @RestControllerAdvice , @SessionAttribute , and @SessionAttributes .
Matrix variables can be used with @MatrixVariable but require enabling support:
<mvc:annotation-driven enable-matrix-variables="true"/>Programmatic enabling via Java configuration:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}Spring Boot Annotations
@EnableAutoConfiguration tells Spring Boot to automatically configure beans based on the classpath.
@SpringBootApplication is a convenience annotation that combines @Configuration , @EnableAutoConfiguration , and @ComponentScan for the main application class.
Stereotype Annotations
@Component declares a generic Spring bean.
@Service and @Repository are specializations of @Component for service and data‑access layers, respectively. The latter also enables exception translation.
Data Access Annotation
@Transactional marks a class or method as participating in a transaction. It is metadata consumed by transaction‑management infrastructure.
Task Execution and Scheduling Annotations
@Scheduled schedules a method for periodic execution. Example with fixed delay and fixed rate:
@Scheduled(fixedDelay = 1000)
public void schedule() { }
@Scheduled(fixedRate = 1000)
public void schedulg() { }@Async runs a method asynchronously in a separate thread. The method may return a Future or be void.
Testing Annotations
Integration tests can be configured with @RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration to load the Spring context:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest { }These annotations together provide a comprehensive, annotation‑driven approach to building, configuring, testing, and operating modern Spring‑based Java applications.
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.