Spring Boot에서 @PostConstruct 알아보자!

Karim·2022년 7월 22일
3

SpringBoot

목록 보기
7/15
post-thumbnail

1. Version

💬

  • spring boot : 2.6.1

2. @PostConstruct

@PostConstruct 란

  • 의존성 주입완료된 후에 실행되어야 하는 method에 사용
  • 해당 어노테이션은 다른 리소스에서 호출되지 않아도 수행
  • 생성자 보다 늦게 호출된다.

    [호출 순서]

    1. 생성자 호출
    2. 의존성 주입 완료 (@Autowired || @RequiredArgsConstructor )
    3. @PostConstruct

3. 사용 이유

💡

  • 생성자가 호출되었을 때, bean은 초기화 전이다.(DI가 이루어 지기 전) @PostConstruct 를 사용하면, bean이 초기화 됨과 동시에 의존성을 확인할 수 있다.
  • bean lifeCycle에서 오직 한 번만 수행된다. (여러 번 초기화 방지)

4. example

✒️ PostConstructTestService

@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 (Exception e){
            System.out.println("@PostConstruct DI 실패");
        }
    }
}

💻 실행 화면


📌 여담

  • 화이팅!

📚 참고

profile
나도 보기 위해 정리해 놓은 벨로그

0개의 댓글