티스토리 뷰

다음과 같이 스프링 컨테이너를 만들면 

AbstractApplicationContext ctx =
        new AnnotationConfigApplicationContext(AppCtx.class);

스프링은 객체 생성 -> 의존 설정 -> 초기화 -> 소멸 의 과정을 거친다.

 


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

 

빈 객체가 초기화 될때와 소멸 할때, 스프리이 컨테이너는 특정 메소드를 호출하는데 해당 메소드는 다음 두 인터페이스에 정의되 있다.

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

 

DisposableBean 인터페이스에는 destroy() 메소드가, 

InitializingBean 인터페이스에는 afterPropertiesSet() 메소드가 정의되있고,

destroy() 메소드는 빈 객체 소멸시, afterPropertiesSet() 메소드에는 빈 객체 생성시 호출된다. 

 

따라서 빈 객체가 생성될때나 소멸될때 어떤 동작을 수행하고 싶다면 해당 인터페이스를 implement 한 후에 메소드를 오버라이딩 해주면 된다. 

 

package Spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

// Bean 객체의 생성,소멸
public class Client implements InitializingBean, DisposableBean
{
    private String host;

    public void setHost(String host)
    {
        this.host = host;
    }

    // InitializingBean 인터페이스에 존재, 빈 초기화시 실행
    @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.destroy() 실행");
    }

}

 

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

 

스프링의 인터페이스를 사용하지 않고도 빈 객체 초기화와 소멸시 실행할 메소드를 정해줄수 있다.

@Bean 애노테이션의 initMethod와 destroyMethod 속성을 이용한다.

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

이렇게 해주면 client2 빈 객체가 생성되어 초기화될때 connect 이라는 이름의 메소드가 호출되고,

소멸할때 host 라는 이름의 메소드가 호출된다. 

 

 


싱글톤이 아닌 빈 객체 (프로토타입 범위의 빈) 

스프링 컨테이너는 하나의 빈 객체만을 생성하고 이를 싱글톤 범위를 갖는다고 한다.

 

Client client1 = ctx.getBean("client", Client.class);
Client client2 = ctx.getBean("client", Client.class);

즉 이런식으로 빈 객체를 만들었다면 client1과 client2는 같은 객체다.

 

하지만 이렇게 하지 않고 여러개의 빈 객체를 만들고 싶을수도 있다. 

이를 프로토타입 범위의 빈이라고 하고 @Scope 애노테이션에 값을 "prototype"을 주면된다.

@Bean
@Scope("prototype")
public Client client()
{
    Client client = new Client();
    client.setHost("host");
    return client;
}

이렇게 해주면 Client 빈 객체는 프로토타입 범위를 갖게되고 

Client client1 = ctx.getBean("client", Client.class);
Client client2 = ctx.getBean("client", Client.class);
Client client3 = ctx.getBean("client", Client.class);

위 3개의 객체는 모두 다른 객체가 리턴 될 것이다. 

 

 

프로토타입의 범위를 갖는 빈은 완전한 라이프사이클을 따르지 않는다. 

스프링 컨테이너는 프로토 타입 범위를 갖는 빈 객체를 생성, 프로퍼티 설정, 초기화를 수행한다.

하지만 컨테이너를 종료해도 생성한 빈 객체의 소멸 메소드를 실행하지는 않는다. 

따라서 프로토 타입 범위를 갖는 빈 객체에 대해서는 소멸 메소드를 직접 처리해줘야 한다. 

 

 

 

출처 : 스프링5 프로그래밍 입문 (최범균 저) 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함