관리 메뉴

진취적 삶

6.2 스프링 빈 객체의 라이프사이클 본문

스프링 5 프로그래밍 입문/6.빈 라이플사이클봐 범위

6.2 스프링 빈 객체의 라이프사이클

hp0724 2023. 9. 6. 00:10

빈 객체의 라이프 사이클은

객체 생성 → 의존 설정 → 초기화 → 소멸

6.2.1 빈 객체의 초기화와 소멸: 스프링 인터페이스

InitializingBean , DisposableBean

  • InitializingBean 은 초기화 과정에서 afterPropertiesSet() 메서드 실행
  • DisposableBean 은 소멸 과정에서 destroy() 메서드 실행

초기화와 소멸 의 예

  • 데이터 베이스 커넥션 풀

커넥션 풀을 위한 빈 객체는 초기화 과정에서 데이터베이스 연결을 생성한다. 빈객체를 소멸할 때 사용중인 데이터베이스 연결을 끊어야 한다.

  • 채팅 클라이언트 서버와 연결을 생성하고 끊는 작업은 초기화와 소멸
@Configuration
public class AppCtx {
	
	@Bean
	public Client client() {
		Client client = new Client();
		client.setHost("host");
		return client;
		
		
	}
	

}
public class Client implements InitializingBean, DisposableBean {
	
	private String host; 
	
	public void setHost(String host ) {
		this.host =host;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		
		System.out.println("client.afterPropertiesSet 실행 ");
	}
	
	public void send() {
		System.out.println("client.send() to"+host);
	}


	@Override
	public void destroy() throws Exception {
		System.out.println("client.destory() 실행 ");
	}

	
}
public class Main {
	
	public static void main(String[] args) {
		AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(AppCtx.class);
		
		Client client = ctx.getBean(Client.class);
		client.send();
		
		ctx.close();
		
		
	}

}
client.afterPropertiesSet 실행 
client.send() tohost
6월 19, 2023 12:58:21 오후 org.springframework.context.support.AbstractApplicationContext doClose
정보: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@41906a77: startup date [Mon Jun 19 12:58:21 KST 2023]; root of context hierarchy
client.destory() 실행

초기화 먼저 실행 되고 close 메서드 동작하면서 destroy 실행

6.2.2 빈 객체 초기화와 소멸 :커스텀 메서드

public class Client2   {
	
	private String host; 
	
	public void setHost(String host ) {
		this.host =host;
	}
	
	 
	public void connect() {
		
		System.out.println("connect 실행");
	}
	
	public void send() {
		System.out.println("client.send() to"+host);
	}


	 
	public void  close(){
		System.out.println("close () 실행 ");
	}

	
}
@Configuration
public class AppCtx {
	
	@Bean(initMethod = "connect", destroyMethod = "close")
	public Client2 client2() {
		Client2 client = new Client2();
		client.setHost("host");
		return client;
		
		
	}
	

}

@Bean 의 initMethod 와 destroyMethod 에 이름을 지정해주면 된다.

초기화 메서드가 두번 호출되지 않도록 주의해야한다.