Backend

Spring Container(ApplicationContext)와 Bean

연_우리 2022. 3. 28. 15:02
반응형

 

 

 

@Configuration

이 어노테이션을 클래스에 붙이면 해당 클래스를 스프링 설정 클래스로 등록한다.

 

@Bean 빈

스프링이 생성하는 객체를 빈이라고 부른다.

@Bean을 메서드에 붙이면 해당 메서드가 생성한 객체를 스프링이 관리하는 빈 객체로 등록한다.

@Configuration  //AppContext.java를 스프링 설정 클래스로 등록한다
public class AppContext {

    @Bean
    public Greeter greeter(){
        Greeter greeter = new Greeter();
        greeter.setFormat("%s, 안녕하세요.");
        return greeter;
    }
}

 

Greeter타입이고, "greeter" 라는 이름의 Bean이 스프링 컨테이너에 등록된다.

 

 

 

ApplicationContext = Spring Container

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);
//어노테이션 기반의 설정정보를 읽어오기

ApplicationContext ctx = new GenericXmlApplicationContext(AppContext.xml);
//XML기반의 설정정보를 읽어오기

어노테이션, XML기반의 설정정보를 읽어와서 빈 객체를 생성하고 관리하는 Context를 가져온다.

어노테이션기반을 바탕으로 설명하면, AppContext에 정의한 @Bean을 읽어와 "greeter"객체를 생성하고 초기화한다.

 

ApplicationContext는 Bean객체의 생성, 초기화, 보관, 제거 등을 역할을 맡고있다.

=> 객체를 관리하는 것을 Container라고도 부른다.

 

 

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);

        Greeter greeter1 = ctx.getBean("greeter", Greeter.class);
        //스프링 컨테이너에서 Gretter.class타입이고, 이름이 greeter 빈을 가져온다

        Greeter greeter2 = ctx.getBean("greeter", Greeter.class);
        Greeter greeter3 = new Greeter();
        Greeter greeter4 = new Greeter();
        
        System.out.println(greeter1 == greeter2);   //true
        System.out.println(greeter1 == greeter3);   //false
        System.out.println(greeter3 == greeter4);   //false

        ctx.close();
    }
}

greeter1과 greeter2는 같은 주소를 가지고 있다. = 같은 객체이다.

greeter3와 greeter4는 다른 주소를 가지고 있다. = 다른 객체이다.

 

스프링은 컨테이너에 등록된 Bean을 기본적으로 1개만 생성해준다. (싱글톤)

 

 

 

 

 

 

 

BeanFactory

빈 생성과 검색에 대한 기능을 정의하고있다.

 

 

ApplicationContext

BeanFactory를 상속받아서 더 편리하게 빈을 관리할 수 있도록 도와준다.

+ 메시지, 환경변수 등을 처리하는 편리기능을 제공해준다.

 

 

반응형
  • 네이버 블러그 공유하기
  • 페이스북 공유하기
  • 트위터 공유하기
  • 구글 플러스 공유하기
  • 카카오톡 공유하기