1.4 Comprehensive Guide to Key Spring Annotations
The Spring framework handles a significant portion of its configuration through annotations. We've summarized the key annotations by category for easy reference.
@RestController // 1. Controller declaration
@RequiredArgsConstructor // 2. Automatic constructor generation (DI)
public class HelloController {
private final HelloService helloService; // 3. Injection target
@GetMapping("/hello") // 4. HTTP GET mapping
public String hello() { return helloService.greet(); }
}
1. Stereotypes (Bean Registration)
Annotations that let the Spring container recognize a class as a Managed Bean.
- @Component: Basic Spring-managed component. (
@Component public class MyTool { ... }) - @Service: Used for classes handling business logic. (
@Service public class OrderService { ... }) - @Repository: Used for data access (DAO) classes; translates DB exceptions to Spring exceptions. (
@Repository public interface MemberRepository { ... }) - @Controller: Controller that returns a traditional MVC View.
- @RestController: Controller for REST APIs returning data like JSON/XML. (
@RestController = @Controller + @ResponseBody)
2. Dependency Injection (DI)
- @Autowired: Automatically injects a Bean registered in the Spring container. (
@Autowired private MyService service;) - @Qualifier: Specifies which bean to inject when multiple beans of the same type exist. (
@Qualifier("kakaoPayService")) - @Bean: Registers an object returned by a method as a Spring Bean.
- When to use: Used when creating Beans for ** external librariesthat you cannot control directly, or when ** complex initialization logicis required.
- @Configuration: Declares a class as a configuration source, which can contain one or more
@Beandefinitions.
@Configuration
public class AppConfig {
@Bean // Standard object registration
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean // Functional interface (Functional Bean) example
public Function<String, String> upperCaseFunction() {
return (input) -> input.toUpperCase();
}
}
🔍 Comparison: @Component vs @Bean
| Category | @Component | @Bean |
|---|---|---|
| Target | Class | Method |
| Usage | Custom classes created by you | External libraries, configuration classes |
| Registration | Automatically via Component Scan | Manually by returning an instance |
3. Spring MVC (Web Request Handling)
- @GetMapping, @PostMapping: Maps specific HTTP method requests. (
@GetMapping("/list")) - @PathVariable: Extracts variable values from the URL path. (
/users/{id}->@PathVariable Long id) - @RequestParam: Extracts values from query or form parameters. (
?name=abc->@RequestParam String name) - @RequestBody: Converts the HTTP request body (JSON, etc.) into a Java object. (
@RequestBody UserDto dto) - @ResponseBody: Sends the Java object directly to the HTTP response body.
4. Lifecycle and Configuration
- @PostConstruct: Executed after a Bean has been created and dependency injection is complete. (
@PostConstruct public void init() { ... }) - @PreDestroy: Executed right before the container is closed and the Bean is destroyed. (
@PreDestroy public void close() { ... }) - @Value: Injects values from configuration files (
application.yml) into fields. (@Value("${api.key}") private String key;) - @PropertySource: Loads external configuration files (.properties). (
@PropertySource("classpath:db.properties")) - @Lazy: Delays the initialization of a Bean until it is actually needed. (
@Lazy @Component class HeavyObj { ... }) - @Scope: Defines the lifecycle scope of a Bean. (
@Scope("prototype") @Bean ...)
5. Spring Boot Specifics
- @SpringBootApplication: The entry point of a Spring Boot application; enables auto-configuration and component scanning.
- @ConfigurationProperties: Hierarchically binds values from configuration files to an object. (
@ConfigurationProperties(prefix = "mail") class MailProp { ... })
6. Other Important Annotations
- @Transactional: Defines the scope of a database transaction. (
@Transactional(rollbackFor = Exception.class)) - @Valid / @Validated: Triggers the validation of constraint annotations. (
@Valid UserDto dto) - @ExceptionHandler: Handles exceptions that occur within a specific controller. (
@ExceptionHandler(UserException.class)) - @RestControllerAdvice: Globally handles exceptions occurring across all controllers.
🎯 Key Points
- Annotations improve configuration productivity and keep the code concise.
- It's best to clearly distinguish layer responsibilities using Stereotype annotations.
- Understanding whether an annotation works at compile-time or runtime(via reflection) allows for a deeper understanding of the framework.