Lifes Cycle

이한주·2023년 5월 10일
0

Bean Lifecycle Callbacks

Bean 생성 생명주기 콜백

  1. @PostConstruce 애노테이션이 적용된 메소드 호출
  2. Bean이 InitializingBean 인터페이스 구현시 afterPropertiesSet 호출
  3. @Bean 애노테이션이 initMethod에 설정한 메소드 호출

Bean 소멸 생명주기 콜백

  1. @PreDestroy 애노테이션이 적용된 메소드 호출
  2. Bean이 DisposableBean 인터페이스 구현시 destroy 호출
  3. @Bean 애노테이션의 destroyMethod에 설정한 메소드 호출

다음과 같은 코드로 확인할 수 있다.

public class MemoryVoucherRepository implements VoucherRepository, InitializingBean, DisposableBean {

    private final Map<UUID, Voucher> storage = new ConcurrentHashMap<>();

    @Override
    public Optional<Voucher> findById(UUID voucherId) {
        return Optional.ofNullable(storage.get(voucherId));
    }

    @Override
    public Voucher insert(Voucher voucher) {
        storage.put(voucher.getVoucherId(), voucher);
        return voucher;
    }

	// Life Cycle 확인 코드 추가
	@PostConstruct
	public void postConstruct() {
		System.out.println("postConstruct called!");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet called!");
	}

	@PreDestroy
	public void preDestroy() {
		System.out.println("preDestroy called!");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("destroy called!");
	}

실행 결과 콜백 메소드 순서는 다음과 같다.

postConstruct called!
afterPropertiesSet called!
preDestroy called!
destroy called!

Process finished with exit code 0

빈을 정의할 때 @Bean 어노테이션의 initMethod 속성을 이용해 초기화 메소드를 지정할 수 있다.

@Configuration
public class AppConfiguration {

	@Bean(initMethod = "init")
	public BeanOne beanOne() {
		return new BeanOne();
	}
}

class BeanOne implements InitializingBean {

	public void init() {
		System.out.println("[BeanOne] init called!");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("[BeanOne] afterPropertiesSet called!");
	}
}

실행 결과는 다음과 같고 init 메소드가 나중에 실행된다.

0개의 댓글