@PostoConstruct 란?
- 종속성 주입이 완료된 후 실행되어야 하는 메서드에 사용, 의존성 주입이 완료된 후에 실행되어야 하는 메소드에 사용
- 다른 리소스에서 호출되지 않아도 수행
- 생성자보다 늦게 호출이된다
※ 호출순서
1. 생성자 호출
2. 의존성 주입 완료 (@Autowire || @RequiredArgsConstructor)
3. @PostConstruct
@PostConstruct 사용 이유
1) 생성자 호출 시, bean은 초기화가 이루어지기 전! (= DI가 이루어지기 전)
따라서, @Postconstruct를 사용하면 bean이 초기화 되는 동시에 의존성 확인이 가능!
2) bean LifeCycle 에서 오직 한 번만 수행 된다. (= 어플리케이션이 실행될 때 한 번만 실행)
3) bean이 여러 번 초기화되는걸 방지
example
@Service
public class PostConstructTestService {
@AutoWired
TestMapper testMapper;
// 생성자
public PostConstructTestService() {
System.out.println("PostConstructTestService 생성자 호출 시기");
try {
testMapper.getTest();
} catch (Exception e) {
System.out.println("생성자 DI 실패");
}
}
@PostConstruct
public void init() {
System.out.println("PostConstructTestService @PostConstruct 호출");
try {
testMapper.getTest();
} catch (Exceptrion e) {
System.out.println("@PostConstruct DI 실패");
}
}
}
example 실행 모습
PostConstructTestService 생성자 호출 시기
생성자 DI 실패
PostConstructTestService @PostConstruct 호출
728x90