본문 바로가기
Spring

스프링이 Bean 객체를 관리하는 방법

by 자바지기 2022. 11. 6.
반응형

Bean 객체란?

스프링이 생성하고 관리하는 객체를 Bean 객체라고 한다.

 

아래의 예시를 통해 학습을 진행해보자.

@Configuration
public class AppContext {

    @Bean
    public Member 멤버() {
        return new Member("박성우");
    }
}

@Configuration 애노테이션은 해당 클래스를 스프링 설정 클래스로 지정한다.

@Bean 애노테이션을 붙인 메서드가 반환하는 객체를 스프링에서 관리한다.


메서드의 이름인 멤버는 빈 객체를 구분할 때 사용된다.

멤버라는 이름을 가진 빈 객체를 조회하면 미리 저장되어있던 Member("박성우") 객체가 반환된다.

 

빈 객체 등록과 조회는 다음처럼 진행할 수 있다.

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = 
        	new AnnotationConfigApplicationContext(AppContext.class);
            
        Member 멤버 = ctx.getBean("멤버", Member.class);  
        // Bean 등록 할 때의 메서드 이름이 `멤버`였으므로 `멤버`로 조회해야한다.

        System.out.println(멤버.getName());
        ctx.close();
    }
}

 

 

AnnotationConfigApplicationContext는 무엇일까?

 

AnnotationConfigApplicationContext는 자바 설정에서 정보를 읽어서 Bean 객체를 생성하고 관리한다.

즉, 내가 정의한 AppContext라는 클래스를 읽어서 클래스 내부에 정의한 @Bean 애노테이션을 통해 Bean 객체를 생성하고 관리한다.

 

AnnotationConfigApplicationContext 클래스는 ApplicationContext라는 인터페이스를 구현한다.

 

ApplicationContext 구현한 클래스는 AnnotationConfigApplicationContext뿐만 아니라 여러가지가 존재한다.

AnnotationConfigApplicationContext는 애노테이션을 이용하여 설정을 진행하는 경우 사용되는 클래스이고,
XML 파일이나 그루비 설정 코드를 이용하여 객체 생성/초기화를 수행하는 경우에 사용되는 클래스들도 존재한다.

 

각 구현 클래스들은 Bean 객체를 생성하고 그 객체를 구현 클래스 내부에 보관한다.
따라서 이러한 ApplicationContext는 Bean 객체의 생성, 초기화, 보관, 제거 등을 관리하므로 컨테이너 라고도 불린다.

컨테이너의 존재를 확인해보기 위해 코드를 살펴보았다.

1. AnnotationConfigAppicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);

위의 코드가 실행되면 Bean 등록이 일어나게 된다.

AnnotationConfigApplicationContext는 상위 클래스 GenericApplicationContext를 상속받는다.

GenericApplicationContext는 내부적으로 DefaultListableBeanFactory를 갖는다.

image

DefaultListableBeanFactory 상위에는 DefaultSingletonBeanRegistry 클래스가 존재한다.

AppContext 클래스 내부에 정의한 Bean 객체는 다음과 같이 DefaultSingletonBeanRegistry 클래스의 내부 필드 singletonObjects에 저장된다.

image

결과적으로 Bean으로 등록된 Member 객체는 AnnotationConfigApplicationContext 내부에 존재하는 셈이다.

 

말이 너무 어렵다. 그림으로 보면 다음과 같다.

image

2. Member 멤버 = ctx.getBean("멤버", Member.class);

위의 코드를 실행하면 이전에 저장했던 singletonObjects에서 멤버라는 이름을 가지는 Bean을 꺼내온다.

image

이로써 ApplicationContext을 상속받은 AnnotationConfigApplicationContext이 Bean 객체의 생성, 초기화, 보관을 관리하는 것을 확인해보았다.
AnnotationConfigApplicationContext뿐만 아니라 다른 구현체들 또한 같은 방식으로 동작한다.
구현체들은 모두 GenericApplicationContext를 상속받고있기 때문이다.

반응형

'Spring' 카테고리의 다른 글

Bean 객체의 생성과 소멸  (0) 2022.11.13
@Component란?  (0) 2022.11.13
@Qualifier 알아보기  (0) 2022.11.08
스프링 DI란?  (0) 2022.11.06

댓글