Bean 객체들의 만남의 광장 : AnnotationConfigApplicationContext

2023. 5. 30. 15:46치고 빠지는 간단한 찍먹 정보

728x90
SMALL

AnnotationConfigApplicationContext

AnnotationConfigApplicationContext 은 Bean으로 지정된 객체들을 가지고 있는 context 입니다.

컨테이너라고도 부릅니다.

 

AnnotationConfigApplicationContext 을 통해 현재 어떤 Bean 객체들이 관리되고 있는지 확인할 수 있고 개수도 확인할 수 있으며, getBean 함수를 통해 특정 Bean 객체를 호출하여 해당 객체 내부에 있는 함수 기능도 사용할 수 있습니다.

 

@Configuration
@ComponentScan("com.udemy.learnspringframework.app1.game") // Component로 선언된 객체가 있는 경로로 가서 해당 객체를 자동으로 Bean 객체 생성 주입
public class GamingAppLauncherApplication {

    public static void main(String[] args) {

        try (var context = new AnnotationConfigApplicationContext(GamingAppLauncherApplication.class)) {
            context.getBean(GamingConsole.class).up();
            context.getBean(GameRunner.class).run();
        }

    }
}

예시의 코드를 통해 설명하자면,

1. @Configuration 어노테이션을 통해 설정 객체로 지정.

2. @ComponentScan("경로") 어노테이션을 통해 해당 경로에 있는 Component 객체들을 스캔 후 Bean 객체 등록

3. var context = new AnnotationConfigApplicationContext(GamingAppLauncherApplication.class) 를 통해 현재 Configuration 어노테이션으로 설정 클래스로 지정된 현 클래스를 AnnotationConfigApplicationContext에 넣고 초기화하여 var 타입 변수에 넣음.

(현재 GamingAppLauncherApplication 에는 ComponentScan 으로 인해 등록된 여러 Bean 객체들을 가지고 있는 상태라고 볼 수 있음. 따라서 AnnotationConfigApplicationContext에 넣음으로 인해 현 GamingAppLauncherApplication 클래스에 가지고 있는 Bean 객체들을 확인할 수 있음.)

4. .getBean() 함수를 통해 특정 Bean 객체(GamingConsole.class, GameRunner.class)를 가지고 와서 그 객체에 존재하는 up 함수와 run 함수를 실행.

 

 

# .getBean 함수에 class 타입을 넣어서 호출할 수도 있지만, @Configuration 으로 설정된 설정 클래스 객체 내부에 존재하는 @Bean 으로 지정된 함수명으로 호출할 수 있습니다. .getBean("{Bean 함수 객체 명}")

@Configuration
public class HelloWorldConfiguration {

    @Bean
    public String name(){
        return "세훈";
    }

    @Bean
    public int age(){
        return 28;
    }

    @Bean
    public Person person(){
        var person = new Person("진세훈", 27, new Address("대한민국", "서울"));

        return person;
    }
}


////////////////////////////////////////////////////////////////////////////////////////////


public class App02HelloWorldSpringJava {

    public static void main(String[] args) {
        // 스프링은 객체에 대한 제어권을 가지고 스스로 제어할 수 있다.
        // 1. 스프링 컨텍스트 실행
        // @Configurtaion 으로 지정된 HelloWorldConfiguration 설정 객체를 AnnotationConfigApplicationContext로 스프링 컨텍스트 호출한다.
        try (var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class)) {
            // 2. @Configuration 으로 스프링 빈 설정 클래스 객체 생성
            // 설정 클래스 내부에 존재하는 함수에 @Bean 어노테이션을 넣어 Bean 객체로 지정.
            // .getBean 으로 Bean 메소드를 소환. (안에 "Bean 메소드 명") 을 넣어준다.
            System.out.println(context.getBean("name")); // @Bean 으로 지정된 name을 메소드명으로 가진 Bean 메소드 호출
            System.out.println(context.getBean("age"));
            System.out.println(context.getBean("person"));
        }
        
    }
}

 

728x90
반응형
LIST