@PreDestory란?

2020. 11. 12. 17:06OpenSource/Spring

반응형

이 메소드는 소멸 메소드이며 이전 @PostConstruct와 상반된 개념이다.

JSR-250 스펙에 따라 구현 되었다.

(걍 자바에서 사용하려면 또는 springframework 2.5미만 버전에서는 javax.annotation 패키지 관련 라이브러리가 필요 함.)

Springframework 2.5부터는 사용 가능!

 

현재 프로젝트에서는 @PostConstruct와 @PreDestory만 사용하고 있다.

하지만 찾아보니 여러가지 방법이 존재했다.

 

아래의 멋진 사이트를 참고하면 된다. 정리 및 공유 감사용!

madplay.github.io/post/spring-bean-lifecycle-methods

 

그 중 흥미로운 테스트가 있었는데

바로 생성자/소멸자 호출 순서 테스트이다. 

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MadplayApplication {

	@Bean(initMethod = "initTaengPonent", destroyMethod = "destoryTaengPonent")
	public TaengPonent initTaengPonent() {
		return new TaengPonent();
	}

	public static void main(String[] args) {
		SpringApplication.run(MadplayApplication.class, args);
	}
}

class TaengPonent implements InitializingBean, DisposableBean {

	@Override
	public void afterPropertiesSet() {
		System.out.println("afterPropertiesSet");
	}

	public void initTaengPonent() {
		System.out.println("initTaengPonent");
	}

	@PostConstruct
	public void postConstruct() {
		System.out.println("postConstruct");
	}

	@Override
	public void destroy() {
		System.out.println("destroy");
	}

	public void destoryTaengPonent() {
		System.out.println("destoryTaengPonent");
	}

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

결과는 아래와 같다.

postConstruct
afterPropertiesSet
initTaengPonent
preDestroy
destroy
destoryTaengPonent
Bash

결론적으로 @PostDestory는 스프링 컨테이너에 있는 Bean이 소멸(Destory)하기전에 수행되는 녀석이다.

메소드에 사용되는 어노테이션(annotation)이며 AbstractApplicationContext > context.close()하기전에 수행한다.

참고 : Close this application context, destroying all beans in its bean factory.

 

반응형

'OpenSource > Spring' 카테고리의 다른 글

Jackson Annotation Examples  (0) 2020.11.17
@Retryable  (0) 2020.11.17
@PostConstruct란?  (0) 2020.11.10
Spring WebFlux  (0) 2017.04.26
ChainedTransactionManager를 이용한 글로벌트랜잭션  (0) 2013.08.22