@Autowired 빈 주입 방식 3가지
- 생성자
- 필드
- Setter
@Autowired와 빈 주입 과정 이해
@Autowired로 빈을 주입할 때, required = false 옵션을 사용하면 빈 주입이 이루어지지 않아도 객체가 생성될 수 있다. 하지만 생성자 주입 방식은 주입할 빈이 반드시 필요하므로, 주입 대상 빈이 없으면 객체 생성에 실패한다.
@Component
public class ExampleService {
private final DependencyService dependencyService;
// 생성자 주입
@Autowired
public ExampleService(DependencyService dependencyService) {
this.dependencyService = dependencyService;
}
@PostConstruct
public void setup() {
// PostConstruct 단계에서 dependencyService는 이미 주입된 상태
System.out.println("DependencyService has been injected: " + dependencyService);
dependencyService.performAction();
}
}
@Autowired를 통한 빈 주입은 AutowiredAnnotationBeanPostProcessor에 의해 이루어진다. 이 작업은 Spring 생명주기의 postProcessBeforeInitialization 단계에서 실행된다. 따라서 @PostConstruct로 실행되는 메서드에서는 이미 빈이 주입된 상태로 실행된다.
'Programming > Spring' 카테고리의 다른 글
ApplicationEventPublisher (0) | 2024.12.13 |
---|---|
@Component와 @Bean (0) | 2024.12.12 |
ApplicationContext 2가지 빈 설정 방식 (0) | 2024.12.11 |
RequestBody 자바 객체 매핑 (0) | 2024.12.11 |
MapStruct & Lombok 적용 (0) | 2022.05.04 |