SPRING
[SPRING] 빈 등록 초기화, 소멸 메소드
혀내
2022. 7. 21. 18:50
반응형
@Bean(initMethod = "method 명", destroyMethod = "method 명")
- Config 클래스에서 빈을 등록할 때 초기화 또는 소멸 메소드도 함께 지정할 수 있다.
- 스프링 뿐만 아니라 외부 라이브러리에서도 적용할 수 있다.
- destroyMethod를 설정하지 않으면 기본적으로 'close', 'shutdown' 이름의 메소드를 자동으로 호출한다.
- 소멸 메소드를 사용하고 싶지 않다면 빈 공백으로 남겨두도록 하자!
예시
@Configuration
class LifeCycleConfig {
@Bean(initMethod = "init", destroy = "close")
public NetworkClient networkClient() {
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
NetworkClient 클래스
public class NetworkClient {
private String url;
public NetworkClient() {
System.out.println("생성자 호출, url = " + url);
}
public void init() {
System.out.println("initialize NetworkClient");
connect();
call("초기화 연결 메시지");
}
public void close() {
System.out.println("close NetworkClient");
disconnect();
}
..
}
@PostConstruct, @PreDestroy
- @Bean에 따로 명시하지 않고도 초기화, 소멸 메소드를 지정할 수 있는 방법이다.
- 편리해 가장 많이 사용되지만, 외부 라이브러리에는 적용하지 못한다.
@Component
public class NetworkClient {
private String url;
public NetworkClient() {
System.out.println("생성자 호출, url = " + url);
}
@PostConstruct
public void init() {
System.out.println("initialize NetworkClient");
connect();
call("초기화 연결 메시지");
}
@PreDestroy
public void close() {
System.out.println("close NetworkClient");
disconnect();
}
..
}
출처:
스프링 핵심 원리 - 기본편 - 인프런 | 강의
스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...
www.inflearn.com
반응형