스프링 빈은 객체를 생성하고, 의존관계 주입이 다 끝난 다음에야 필요한 데이터를 사용 할 수 있는 준비가 완료된다.
따라서 초기화 작업은 의존관계 주입이 모두 완료되고 난 다음에 호출해야한다.
스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려주는 다양한 기능을 제공한다.
또한, 스프링은 스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준다.
스프링 빈의 이벤트 라이프 사이클
스프링 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입 → 초기화 콜백 → 사용 → 소멸전 콜백 → 스프링 종료
초기화 콜백 : 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출
소멸전 콜백 : 빈이 소멸되기 직전에 호출
※ 객체의 생성과 초기화를 분리하자.
생성자는 필수 정보(파라미터)를 받고, 메모리을 할당해서 객체를 생성하는 책임을 가진다. 반면에 초기화는 이렇게 생성된 값들을 활용해서 외부 커넥션을 연결하는 등 무거운 동작을 수행한다.
따라서 생성자 안에서 무거운 초기화 작업을 함께하는 것 보다는 객체를 생성하는 부분과 초기화하는 부분을 명확하게 나누는것이 유지보수 관전에서 좋다.
스프링은 크게 3가지 방법으로 빈 생명주기 콜백을 지원
- 인터페이스(InitializingBean, DisposableBean)
- 설정 정보에 초기화 메서드 ,종료 메서드 지정
- @PostConstruct, @PreDestory 어노테이션 지원
인터페이스(InitializingBean, DisposableBean)
public class NetworkClient implements InitializingBean, DisposableBean {
private String url;
public NetworkClient(){
System.out.println("생성자 url = " + url);
}
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);
}
@Override
public void destroy() throws Exception {
connect();
call("초기화 연결");
}
@Override
public void afterPropertiesSet() throws Exception {
disconnect();
}
}
Test
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest(){
ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient networkClient = ac.getBean(NetworkClient.class);
ac.close();
}
@Configuration
static class LifeCycleConfig {
@Bean
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
결과
17:38:32.650 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@52e6fdee
17:38:32.729 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:38:33.233 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
17:38:33.238 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:38:33.240 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
17:38:33.243 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
17:38:33.266 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanLifeCycleTest.LifeCycleConfig'
17:38:33.273 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'networkClient'
생성자 url = null
close = http://hello-spring.dev
17:38:33.417 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@52e6fdee, started on Tue Mar 28 17:38:32 KST 2023
connect =http://hello-spring.dev
call = http://hello-spring.dev, message =초기화 연결
▶ 스프링 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입이 끝난 시점에 초기화콜백 → 소멸 전 콜백
초기화,소멸 인터페이스 단점
- 이 인터페이스는 스프링 전용 인터페이스이다. 해당 코드가 스프링 전용 인터페이스에 의존한다.
- 초기화, 소멸 메서드의 이름을 변경 할 수 있다.
- 내가 코드를 고칠수 없는 외부 라이브러리에 적용 할 수 없다.
설정 정보에 초기화 메서드 ,종료 메서드 지정
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("connect =" + url);
}
public void call(String message) {
System.out.println("call = " + url + ", message =" + message);
}
//서비스 종료시 호출
public void disconnect() {
System.out.println("close = " + url);
}
public void init() {
connect();
call("초기화 연결");
}
public void close() {
disconnect();
}
}
Test
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest(){
ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient networkClient = ac.getBean(NetworkClient.class);
ac.close();
}
@Configuration
static class LifeCycleConfig {
@Bean(initMethod = "init", destroyMethod = "close")
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
설정 정보 사용 특징
- 메서드 이름을 자유롭게 줄 수 있다.
- 스프링 빈이 스프링 코드에 의존하지 않는다.
- 코드가 아니라 설정 정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 종료 메서드를 적용 할 수 있다.
종료 메서드 추론
- @Bean의 'destoryMethod' 속성에는 아주 특별한 기능이 있다.
- 라이브러리는 대부분 'close', 'shutdown'이라는 이름의 종료 메서드를 사용한다.
- @Bean의 'destoryMehtod' 는 기본 값이 (inferred ) (추론)으로 등록되어있다.
- 추론 기능은 'close', 'shutdown' 라는 이름의 메서드를 자동으로 호출해준다. 이름 그대로 종료 메서드를 추론해서 호출한다.
- 따라서 직접 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작한다.
- 추론기능을 사용하기 싫으면 destoryMethod ="" 공백을 지정하면된다.
@PostConstruct, @PreDestory 어노테이션 지원
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
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("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() {
connect();
call("초기화 연결");
}
@PreDestroy
public void close() {
disconnect();
}
}
Test
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest(){
ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient networkClient = ac.getBean(NetworkClient.class);
ac.close();
}
@Configuration
static class LifeCycleConfig {
@Bean
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
@PostConstruct, @PreDestory 어노테이션 특징
- 최신 스프링에서 가장 권장하는 방법이다.
- 어노테이션 하나만 붙이면 되기때문에 편리하다.
- 단점으로 외부 라이브러리에는 적용하지 못하는 것이다. 외부 라이브러리를 초기화, 종료 해야한다면 @Bean의 기능을 사용하자.
강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)