Spring 개념정리

[Spring] 빈 라이프사이클과 범위

개발자 문문 2025. 6. 30. 22:45

안녕하세요 개발자 문문입니다.

오늘은 빈 라이프사이클과 범위에 대해 공부하겠습니다.

 

  • 컨테이너 초기화와 종료
//컨테이너 초기화       
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);

//컨테이너에서 빈 객체를 구해서 사용
Greeter g = ctx.getBean("greeter", Greeter.class);
String msg = g.greet("스프링");
System.out.println(msg);
  
//컨테이너 종료
ctx.close();

 

아래는 컨테이너 초기화, 종료할 때의 작업입니다.

- 컨테이너 초기화 : 빈 객체의 생성, 의존 주입, 초기화

- 컨테이너 종료 : 빈 객체의 소멸

 

이처럼 컨테이너 초기화/종료에 따라 빈 객체도 생성/소멸 이라는 라이프 사이클을 갖게 됩니다.

 

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

 

- 빈 객체의 초기화와 소멸

  • 빈 객체 초기화(InitializingBean)
public interface InitializingBean {
	void afterPropertiesSet() throws Exception;
}

   - 빈 객체가 InitailizingBean을 구현하면 초기화 과정에서 afterPropertiesSet() 메서드를 실행합니다.

   - 빈 객체 생성 뒤 초기화가 필요하다면 InitailizingBean을 상속하고 afterPropertiesSet() 메서드를 구현하면 됩니다.

 

  • 빈 객체 소멸(DisposableBean)
public interface DisposableBean {
	void destroy() throws Exception;
}

   - 빈 객체가 DisposableBean을 구현 했다면 소멸 과정에서 destory() 메서드를 실행합니다.

   - 빈 객체 소멸 과정이 필요하면 DisposableBean을 상속하고 destroy() 메서드를 구현하면 됩니다.

 

Ex) 커넥션 풀( 초기화 : DB 연결, 소멸 : 연결 해제 ) / 채팅 클라이언트 ( 초기화 : 서버 연결 , 소멸 : 서버 연결 해제 )

 

  • 커스텀 메서드
public class Client2{

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

	public void send()
	{
		System.out.println("Client2.send() to "+host);
	}
	
	public void close()
	{
		System.out.println("Client2.close() 실행");
	}
}
@Bean(initMethod = "connect", destroyMethod = "close")
public Client2 client2()
{
    Client2 client = new Client2();
    client.setHost("host");
    return client;
}

- 직접 초기화/소멸시 실행하는 메서드를 커스텀하고 싶다면 @Bean의 initMethod(초기화)destroyMethod(소멸) 속성을 사용하면 됩니다.

 

  • 빈 객체의 생성과 관리 범위

    - 빈은 별도의 설정을 하지 않으면 싱글톤 범위를 갖습니다.

    - 만약 프로토타입 범위의 빈을 설정하려면 @Scope("prototype")을 @Bean과 함께 써주면 됩니다.

    - 하지만 프로토타입 범위의 빈은 완전한 라이프사이클을 따르지 않기 때문에 소멸은 직접 코드에서 처리해줘야 합니다.

      (초기화는 수행)