// 1. 컨테이너 초기화
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppContext.class);
// 2. 컨테이너에서 빈 객체를 구해서 사용
Greeter g = ctx.getBean("greeter", Greeter.class);
String msg = g.greet("스프링");
System.out.println(msg);
// 3. 컨테이너 종료
ctx.close();
빈 객체의 라이프 사이클 :
: 객체 생성 → 의존 설정 → 초기화 → 소멸
[ 기본 방법 ]
스프링 컨테이너를 초기화 할 때,
스프링 컨테이너는 가장 먼저 빈 객체를 생성하고 의존을 설정
모든 의존 설정이 완료되면, 빈 객체의 초기화를 수행(빈 객체의 지정된 메서드 호출)
InitializingBean 인터페이스의 afterPropertiesSet() 호출
컨테이너 종료 시, 빈 객체의 소멸을 처리(지정한 메서드 호출)
DisposableBean 인터페이스의 destroy() 호출
// InitializingBean, DisposableBean 상속받음
public class Client implements InitializingBean, DisposableBean {
private String host;
public void setHost(String host) {
this.host = host;
}
@Override
public void destroy() throws Exception {
System.out.println("Client.destroy() 실행");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Client.afterPropertiesSet() 실행");
}
public void send() {
System.out.println("Client.send() to " + host);
}
}
[ 커스텀 메서드 ]
@Bean 어노테이션의 initMethod, destroyMethod 속성을 사용한다.
@Bean(initMethod = "connect", destroyMethod = "close")
public Client2 client2() {
Client2 client = new Client2();
client.setHost("host");
return client;
}
☠️ 초기화 메서드를 직접 실행할 때 초기화 메서드가 두 번 불리지 않도록 주의 ☠️
@Scope(”prototype”)
프로토타입 범위를 갖는 빈은
스프링 컨테이너가 프로토타입의 빈 객체를 생성하고 프로퍼티를 설정하고 초기화 작업까지는 수행하지만, 컨테이너가 종료된다 하더라도, 소멸 메서드를 실행하지 않는다.
따라서 소멸처리를 직접 코드에서 해야한다.
[ 빈 스코프 ]
책 - 초보 웹 개발자를 위한 스프링 5 프로그래밍 입문
Claude.ai