JAVA

@PostConstruct, @PreDestroy

Strickland 2024. 4. 26. 10:24

애노테이션 @PostConstruct, @PreDestroy

 

아래 코드를 확인하자 

package hello.core.lifecycle;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class NetworkClient {
    private String url;

    public NetworkClient() {

        System.out.println("생성자 호출, url = " + url);


    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void connect() {
        System.out.println("connnet: " + url);
    }

    public void call(String message) {
        System.out.println("call: " + url + " message = " + message);

    }

    public void disconnect() {
        System.out.println("close " + url);

    }


    @PostConstruct
    public void init() {
        System.out.println("NetworkClient.init");
        connect();
        call("초기화 연결");
    }


    @PreDestroy
    public void close() {
        System.out.println("NetworkClient.close");
        disconnect();
    }
}

 

@Configuration
static class LifeCycleConfig {
 @Bean
 public NetworkClient networkClient() {
 NetworkClient networkClient = new NetworkClient();
 networkClient.setUrl("http://hello-spring.dev");
 return networkClient;
 }
}

 

 

실행 결과

@PostConstruct , @PreDestroy 이 두 애노테이션을 사용하면 가장 편리하게 초기화와 종료를 실행할 수 있다 

 

 

'JAVA' 카테고리의 다른 글

빈 스코프  (1) 2024.04.28
Server 란?  (1) 2024.04.26
특정 타입의 스프링 빈이 모두 필요할 때  (0) 2024.04.26
@Qulifier, @Primary  (0) 2024.04.26
컴포넌트 스캔  (0) 2024.04.25