InitializingBean vs @PostConstruct

최창효·2024년 3월 2일
post-thumbnail

InitializingBean과 @PostConstruct어노테이션은 빈의 생명주기 콜백과 관련된 기능입니다.
둘 다 빈이 생성된 후 어떠한 동작을 실행할 수 있게 해주는 기능입니다.

InitializingBean

InitializingBean은 인터페이스입니다. 해당 인터페이스는 afterPropertiesSet이라는 메서드를 가지고 있습니다.
해당 메서드는 스프링의 의존관계 주입이 모두 끝난 뒤 호출됩니다.

사용 방법은 간단합니다. InitializingBean인터페이스를 구현하고 afterPropertiesSet메서드에 실행할 동작을 정의하면 됩니다.

@Component
public class MyClass implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        // something to do
    }
}

@PostConstruct

@PostConstruct는 메서드에 적용 가능한 어노테이션입니다.

@PostConstruct가 붙은 메서드를 가진 클래스는 의존성 주입기술을 지원해야 합니다.

InitializingBean보다 더 사용방법이 간단합니다. 메서드에 @PostConstruct어노테이션을 붙이기만 하면 됩니다.

@Component 
public class MyClass { 
	@PostConstruct
    public void myMethod() {
    	// something to do
    }
}
  • @PostConstruct어노테이션이 붙은 메서드는 매개변수를 가져서는 안됩니다.

  • 하나의 클래스에는 하나의 @PostConstruct만 사용하는 걸 권장합니다.

뭘 써야 할까?

  • 스프링은 @PostConstruct의 사용을 적극 권장하고 있습니다.

    We recommend that you do not use the InitializingBean interface, because it unnecessarily couples the code to Spring. Alternatively, we suggest using the @PostConstruct annotation or specifying a POJO initialization method. - 스프링 공식문서 -

@PostConstruct를 권장하는 이유는 다음과 같습니다.

  • POJO기술이라 스프링이 아닌 다른 컨테이너에서도 사용 가능합니다. (InitializingBean은 스프링 종속적인 기술이라 불가능)
    • PostConstruct의 패키지는 jakarta.annotation
    • InitializingBean의 패키지는 org.springframework.beans.factory
  • 사용법이 간단합니다.
  • 단, @PostConstruct는 외부 라이브러리를 사용할 경우 그 내부 코드를 수정할 수 없어 적용이 불가능할 수 있습니다.

References

profile
기록하고 정리하는 걸 좋아하는 백엔드 개발자입니다.

0개의 댓글