Spring @PostConstruct @PreDestory

과녁스·2021년 7월 14일
0

Spring

목록 보기
1/11
post-thumbnail

개요


스프링 객체의 생성과 제거 단계에서 작업할 수 있는 어노테이션에 대한 학습한 내용을 정리해보았습니다.

@PostConstruct / @PreDetroy


@PostConstruct

  • 객체가 생성되고 별도의 초기화 작업이 필요한 경우 해당 어노테이션 선언 후 메소드 선언
  • @PostConstruct 어노테이션을 설정해놓은 init 메소드는 WAS가 띄워질 때 실행

사용조건

  1. 인자 값이 존재할 수 없다. 인자 값이 존재하는 경우 에러가 발생한다.
    • 어떤 값을 넣어야 할지 알 수 없기 때문
  2. 리턴 타입이 있어도 실행이 되지만 리턴 값을 사용할 방법이 없다.
  3. 하나의 클래스에 여러 개의 PostConstruct가 존재할 수 있다.
// ...
public @Component class InitClass {

	@PostConstruct
    public String init() {
    	System.out.println("PostConstruct1");
    }
    
    @PostConstruct
    public String init2() {
    	System.out.println("PostConstruct2");
    }
    
}
//...
@SpringBootApplication
public class ExampleApplication {

	@Autowired
    private InitClass initClass;
    
    public static void main(String[] args) {
    	SpringApplication.run(ExampleApplication.class, args);
    }
}

@PreDestroy

  • 스프링 어플리케이션 컨텍스트에서 bean을 제거하기 직전에 한 번 실행
  • 스프링 컨테이너에서 객체를 제거하기 전 작업이 필요하다면 어노테이션 사용 후 메서드 선언
  • close() 하기 전 실행 : ((AbstractApplicationContext) context).close()

예제

@PostConstruct
public void initConstruct(){
    System.out.println("초기화");
}

@PreDestroy
public void destroySpring(){
    System.out.println("종료 바로 전");       
}
profile
ㅎㅅㅎ

0개의 댓글