PostConstruct 및 PreDestroy

Soo·2024년 3월 5일

이번 기록은 PostConstruct 와 PreDestroy를 왜?? 어떻게?? 어디에 사용해야하는 지 알아보겠습니다.

PostConstruct 및 PreDestroy 모두 Spring과 함께 사용할 수 있는 아주 중요한 어노테이션입니다.

코드로 보겠습니다.

SomeClass에서 SomeDependency를 데이터베이스로 사용하고 데이터를 가져와 초기화하려는 작업을 할 경우 의존성을 주입받은 후 초기화를 실행하려면 어떻게 해야 할까요?

package com.in28minutes.learnspringframework.example.f1;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
class SomeClass {
    private SomeDependency someDependency;

    public SomeClass(SomeDependency someDependency) {
        super();
        this.someDependency = someDependency;
        System.out.println("All dependencies are ready!");
    }

    public void initialize() {
        someDependency.getReady();
    }
}

@Component
class SomeDependency {

    public void getReady() {
        System.out.println("Some logic using SomeDependency");
    }
}

@Configuration
@ComponentScan
public class PrePostAnnotationsContextLauncherApplication {
    public static void main(String[] args) {

        try (var context = new AnnotationConfigApplicationContext
                (PrePostAnnotationsContextLauncherApplication.class)) {
            Arrays.stream(context.getBeanDefinitionNames())
                    .forEach(System.out::println);
        }
    }
}

바로 @PostConstruct를 사용하면 됩니다.

initialize() 위에 @PostConstruct를 붙여줍니다.

@Component
class SomeClass {
    private SomeDependency someDependency;

    public SomeClass(SomeDependency someDependency) {
        super();
        this.someDependency = someDependency;
        System.out.println("All dependencies are ready!");
    }

		@PostConstruct
    public void initialize() {
        someDependency.getReady();
    }
}

결과

All dependencies are ready!
Some logic using SomeDependency
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
prePostAnnotationsContextLauncherApplication
someClass
someDependency

모든 의존성이 준비가 된 후 초기화를 합니다. 그 후에 initialize() 메서드가 호출이 되고 Some logic using SomeDependency 문자열이 출력됩니다.

Spring은 자동으로 의존성을 연결하고, 의존성을 연결하는 대로 @PostConstruct 어노테이션이 추가된 initialize() 메서드를 호출합니다.

다음으로, 생성 직후 수행할 메서드가 아닌 종료 직전에 수행할 메서드를 알아보겠습니다.

바로, @PreDestroy인데요.

@PreDestroy - 보유하고 있던 리소스를 해제하는 데 사용됩니다.

코드로 보겠습니다.

어떤 데이터베이스 등에 연결되어 있다면 cleanup으로 종료할 수 있습니다.

@Component
class SomeClass {
    private SomeDependency someDependency;

    public SomeClass(SomeDependency someDependency) {
        super();
        this.someDependency = someDependency;
        System.out.println("All dependencies are ready!");
    }

    @PostConstruct
    public void initialize() {
        someDependency.getReady();
    }

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

결과

All dependencies are ready!
Some logic using SomeDependency
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
prePostAnnotationsContextLauncherApplication
someClass
someDependency
Cleanup

컨텍스트에서 Bean이 삭제되기 바로 전에 @PreDestroy 어노테이션이 붙은Cleanup()이 호출됩니다.

0개의 댓글