"Spring이 bean을 어떻게 만들고, 언제 초기화(init)하고, 언제 파괴(destroy)" 하는지 완벽하게 파악하기
Spring Container가 bean을 생성하는 과정
Spring을 사용하면 개발자가 new UserService()와 같이 직접 객체를 만들지 않으며 Spring이 대신 만들어 관리(제어의 역전(IOC), 의존성 주입(DI))를 하는데 정확히 어떤 순서로 만들어 질까?
@Service
public class UserService {
private final EmailService emailService;
@Autowired
public UserService(EmailService emailService) {
System.out.println("1. 생성자 호출");
this.emailService = emailService;
}
@PostConstruct
public void init() {
System.out.println("2. @PostConstruct 호출");
}
@PreDestroy
public void destroy() {
System.out.println("3. @PreDestroy 호출");
}
}
Bean의 정의 읽기 (Component Scan, @Bean 메소드)
Component Scan:
@ComponentScan이 지정된 패키지를 탐색함@Component, @Service, @Repository, @Controller 붙은 클래스 발견@Bean 메소드:
@Configuration 클래스를 탐색@Bean메서드 발견빈(Empty) 인스턴스 생성 (생성자 호출)
의존성 주입 (필드 주입의 경우 여기서, 생성자 주입이면 인스턴스 생성할 때)
@Autowired
private UserRepository repository; // ← 3단계에서 여기에 주입
@Autowired
private EmailService emailService; // ← 3단계에서 여기에 주입
@Service
public class UserService {
private final UserRepository repository;
// 생성자 주입은 2단계에서 함께 처리됨
public UserService(UserRepository repository) {
this.repository = repository;
}
}
AWARE 인터페이스 처리
BeanPostProcessor.postProcessBeforeInitialization()
@PostConstruct 또는 InitializingBean.afterPropertiesSet()
BeanPostProcessor.postProcessAfterInitialization() ⭐(AOP 프록시 생성)
빈 사용 가능
컨테이너 종료 시 @PreDestroy 또는 DisposableBean.destroy