-
Spring 기본 32 - 애노테이션 @PostConstruct,@PreDestoryFrameWork/Spring&Spring-boot 2023. 11. 29. 11:51
애노테이션 @PostConstruct, @PreDestory
NetworkClient
package com.hello.core.lifecycle; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class NetworkClient { private String url; public NetworkClient() { System.out.println("생성자 호출 , url = "+ url); connect(); call("초기화 연결 메시지"); } public void setUrl(String url) { this.url = url; } //서비스 시작시 호출 public void connect(){ System.out.println("connect: "+ 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() throws Exception { //의존 관계주입이 끝나면 호출 되는 메서드 System.out.println("NetworkClient.init"); System.out.println("url = " + url); connect(); call("초기화 연결 메시지"); } @PreDestroy public void close() throws Exception { System.out.println("NetworkClient.close"); disconnect(); } }
BeanLifeCycleTest
package com.hello.core.lifecycle; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class NetworkClient { private String url; public NetworkClient() { System.out.println("생성자 호출 , url = "+ url); connect(); call("초기화 연결 메시지"); } public void setUrl(String url) { this.url = url; } //서비스 시작시 호출 public void connect(){ System.out.println("connect: "+ 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() throws Exception { //의존 관계주입이 끝나면 호출 되는 메서드 System.out.println("NetworkClient.init"); System.out.println("url = " + url); connect(); call("초기화 연결 메시지"); } @PreDestroy public void close() throws Exception { System.out.println("NetworkClient.close"); disconnect(); } }
💡tip) javax 경로
경로가 javax로 시작하면 자바 언어에서 공식적으로 지원하는 기능이라는 의미이다. 따라서 스프링이 아니라 다른 컨테이너 프레임 워크를 쓴다고 하더라도 해당 기능을 사용할 수 있다.
실행결과
`@PostConstruct`, `@PreDestroy`이 두 애노테이션을 사용하면 가장 편리하게 초기화와 종료를 실행할 수 있다.
@PostConstruct, @PreDestroy 애노테이션 특징
- 최신 스프링에서 가장 권장하는 방법이다.
- 애노테이션 하나만 붙이면 되므로 매우 편리하다.
- 패키지를 잘보면 `javax.annotation.PostConstruct`이다. 스프링에 종속적인 기술이 아니라 JSP-250라는 자바 표준이다. 따라서 스프링이 아닌 다른 컨테이너에서도 동작한다.
- 컴포넌트 스캔과 잘 어울린다.
- 유일한 단점은 외부 라이브러리에 적용하지 못한다는 것이다. 외부 라이브러리르 초기화, 종료 해야 하면 @Bean의 기능을 사용하자.
정리
- @PostConstruct, @PreDestroy 애노테이션을 사용하자.
- 코드를 고칠 수 없는 외부 라이브러리를 초기화, 종료해야 하면 `@Bean`의 `initMethod`,`destroyMethod`를 사용하자.
[출처 - 스프링 핵심 원리 - 기본편]
'FrameWork > Spring&Spring-boot' 카테고리의 다른 글
Spring 기본 34 - 프로토타입 스코프 (1) 2023.11.29 Spring 기본 33 - 빈 스코프 (0) 2023.11.29 Spring 기본 31 - 빈 등록 초기화, 소멸 메서드 (0) 2023.11.29 Spring 기본 30 - 인터페이스 IntializingBean, DisposableBean (0) 2023.11.29 Spring 기본 29 - 빈 생명주기 콜 (1) 2023.11.29