Spring ‐ 빈 생명주기 콜백 - dnwls16071/Backend_Study_TIL GitHub Wiki

📚 빈 생명주기 콜백

  • 생성자는 필수 정보를 받아 메모리를 할당해서 객체를 생성하는 책임을 가진다. 반면에 초기화는 이렇게 생성된 값을 활용해서 외부 커넥션을 연결하는 등 무거운 동작을 수행한다.
  • 따라서 생성자 안에서 무거운 초기화 작업을 함께 하기보다는 객체를 생성하는 부분과 초기화하는 부분을 명확하게 하는 것이 좋다.
  • 외부 커넥션을 점유해야하는 경우에는 위와 같이 분리를 하는 것이 적절하나 만약 간단한 객체를 생성하고 초기화하는 경우라면 한 번에 같이 하는 것이 나을수도 있다.
  • 스프링 빈의 이벤트 라이프사이클
    • 초기화 콜백 : 빈이 생성되고 빈의 의존관계 주입 완료 이후 호출
    • 소멸전 콜백 : 빈이 소멸되기 직전에 호출
스프링 컨테이너 생성 - 스프링 빈 생성 - 의존관계 주입 - 초기화 콜백 - 사용 - 소멸전 콜백 - 종료

[ 인터페이스 InitializingBean, DisposableBean ]

public class NetworkClient implements InitializingBean, DisposableBean {

	// ...

        // DisposableBean 인터페이스 메서드 구현
	@Override
	public void destroy() throws Exception {
		disconnect();
	}

        // InitializingBean 인터페이스 메서드 구현
	@Override
	public void afterPropertiesSet() throws Exception {
		connect();
		call("초기화 연결 메시지");
	}
}
class NetworkClientMain {

	@Test
	@DisplayName("빈 생명주기 콜백 by InitializingBean, DisposableBean")
	void lifecycleTest() {

		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(NetworkClientConfig.class);
		NetworkClient networkClient = ac.getBean("networkClient", NetworkClient.class);
		ac.close(); // 스프링 컨테이너 종료
	}

	@Configuration
	static class NetworkClientConfig {

		@Bean
		public NetworkClient networkClient() {
			NetworkClient networkClient = new NetworkClient();
			networkClient.setUrl("http://localhost:8080");
			return networkClient;
		}
	}
}
  • 이 인터페이스는 스프링 전용 인터페이스이다.
  • 초기화, 소멸 메서드 이름을 변경할 수 없다.
  • 스프링 컨테이너를 종료해야 소멸전 콜백이 이루어지게 된다.

테스트 코드 실행 결과

생성자 호출 url = null
Connecting.. http://localhost:8080
call = http://localhost:8080, message = 초기화 연결 메시지
close = http://localhost:8080

[ 빈 등록 초기화, 소멸 메서드 ]

  • 설정 정보에 @Bean(initMethod = "init", destroyMethod = "close")와 같이 초기화, 소멸 메서드를 지정할 수 있다.
public class NetworkClient {

	// ...

	public void init() {
		connect();
		call("초기화 연결 메시지");
	}

	public void close() {
		disconnect();
	}
}
class NetworkClientMain {

	@Test
	@DisplayName("초기화, 소멸 메서드 지정")
	void lifecycleTest() {

		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(NetworkClientConfig.class);
		NetworkClient networkClient = ac.getBean("networkClient", NetworkClient.class);
		ac.close();
	}

	@Configuration
	static class NetworkClientConfig {

		@Bean(initMethod = "init", destroyMethod = "close")	// 여기서 지정
		public NetworkClient networkClient() {
			NetworkClient networkClient = new NetworkClient();
			networkClient.setUrl("http://localhost:8080");
			return networkClient;
		}
	}
}
  • 메서드 이름의 자유로움
  • 스프링 코드에 의존적이지 않다.

테스트 코드 실행 결과

생성자 호출 url = null
Connecting.. http://localhost:8080
call = http://localhost:8080, message = 초기화 연결 메시지
close = http://localhost:8080

[ @PostConstruct, @PreDestroy ]

public class NetworkClient {

	// ...

	@PostConstruct
	public void init() {
		connect();
		call("초기화 연결 메시지");
	}

	@PreDestroy
	public void close() {
		disconnect();
	}
}
class NetworkClientMain {

	@Test
	@DisplayName("초기화, 소멸 메서드 지정")
	void lifecycleTest() {

		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(NetworkClientConfig.class);
		NetworkClient networkClient = ac.getBean("networkClient", NetworkClient.class);
		ac.close();
	}

	@Configuration
	static class NetworkClientConfig {

		@Bean
		public NetworkClient networkClient() {
			NetworkClient networkClient = new NetworkClient();
			networkClient.setUrl("http://localhost:8080");
			return networkClient;
		}
	}
}
  • 최신 스프링에서 권장하는 방법이다.
  • 외부 라이브러리에는 적용할 수 없다.

테스트 코드 실행 결과

생성자 호출 url = null
Connecting.. http://localhost:8080
call = http://localhost:8080, message = 초기화 연결 메시지
close = http://localhost:8080