스프링이해 4- Spring 내부 구조 이해의 끝판
좋습니다 👍
이번에는 Spring Framework에서 면접 단골이면서도 많은 개발자가 정확히 모르는
> Spring Bean 생명주기 (Bean Lifecycle)
를 실제 내부 흐름 기준으로 설명해볼게요.
---
1️⃣ 전체 Bean 생명주기
Spring Bean의 흐름은 크게 이렇게 됩니다.
BeanDefinition 생성
↓
Bean 생성 (Constructor)
↓
의존성 주입 (DI)
↓
초기화 콜백
↓
Bean 사용
↓
컨테이너 종료
↓
소멸 콜백
조금 더 자세히 보면
1 BeanDefinition 등록
2 Bean 생성
3 Dependency Injection
4 Aware 콜백
5 BeanPostProcessor before
6 초기화 (@PostConstruct)
7 BeanPostProcessor after
8 Bean 사용
9 컨테이너 종료
10 Destroy (@PreDestroy)
---
2️⃣ BeanDefinition 단계
Spring이 먼저 하는 일
Bean 메타정보 생성
예
@Service
class UserService {}
이걸 읽어서 내부적으로
BeanDefinition
객체를 만듭니다.
정보 예
클래스 이름
스코프
생성자
의존성
즉
설계도 생성
입니다.
---
3️⃣ Bean 생성
이제 실제 객체 생성
new UserService()
이 단계는 Constructor 실행입니다.
---
4️⃣ Dependency Injection
이제 의존성 주입
예
@Service
class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) {
this.repo = repo;
}
}
Spring이
UserRepository Bean 찾기
↓
Constructor 주입
합니다.
---
5️⃣ Aware 콜백
Spring 내부 인터페이스
예
BeanNameAware
BeanFactoryAware
ApplicationContextAware
예
class MyBean implements ApplicationContextAware
그러면
ApplicationContext 주입
됩니다.
---
6️⃣ BeanPostProcessor (핵심)
이건 Spring 확장 포인트입니다.
인터페이스
BeanPostProcessor
메서드
postProcessBeforeInitialization()
postProcessAfterInitialization()
여기서 하는 일
AOP 프록시 생성
@Transactional 처리
@Async 처리
즉
Spring AOP 기능 대부분이 여기서 만들어집니다.
---
7️⃣ 초기화 콜백
여기서 Bean 초기화
방법 3가지
1️⃣ @PostConstruct
@PostConstruct
public void init() {}
(JSR-250)
---
2️⃣ InitializingBean
afterPropertiesSet()
---
3️⃣ initMethod
@Bean(initMethod="init")
---
8️⃣ Bean 사용
이제 Bean이 정상적으로 사용됩니다.
예
Controller → Service → Repository
---
9️⃣ 컨테이너 종료
Spring 종료 시
ApplicationContext close()
---
🔟 Bean 소멸
소멸 콜백 실행
방법
1️⃣ @PreDestroy
@PreDestroy
public void destroy() {}
---
2️⃣ DisposableBean
destroy()
---
3️⃣ destroyMethod
@Bean(destroyMethod="close")
예
DB 커넥션 정리
---
🔥 실제 전체 흐름
BeanDefinition 생성
↓
Constructor 실행
↓
Dependency Injection
↓
Aware 콜백
↓
BeanPostProcessor before
↓
@PostConstruct
↓
BeanPostProcessor after
↓
Bean 사용
↓
Context 종료
↓
@PreDestroy
---
💡 진짜 중요한 포인트
Spring의 많은 기능이
BeanPostProcessor
에서 만들어집니다.
예
기능 구현
AOP BeanPostProcessor
@Transactional BeanPostProcessor
@Async BeanPostProcessor
@Autowired BeanPostProcessor
즉
> Spring 확장 구조의 핵심
입니다.
---
🔥 한 단계 더 깊은 질문 (면접 고급)
면접에서 자주 이어지는 질문
1️⃣ BeanFactory vs ApplicationContext 차이
2️⃣ Spring이 싱글톤인데 Thread-safe 문제 없는 이유
3️⃣ Prototype Bean은 왜 관리 안 해주는지
4️⃣ Circular Dependency (순환참조) 해결 원리
특히
> Spring이 순환참조를 어떻게 해결하는지 (3단계 캐시)
이건 Spring 내부 구조 핵심이라서
이해하면 Spring 실력 상위 10% 수준 됩니다.
댓글
댓글 쓰기