스프링 컨텍스트, 스프링 빈

wangjh789·2022년 7월 22일
0

스프링 컨텍스트

AppConfig 객체를 직접 생성 -> @Configuration 을 통해 스프링빈으로 등록시키고 AnnotationConfigApplicationContext 으로 컨텍스트를 불러와 빈을 가져옴

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
// AppConfig appConfig = new AppConfig();

MemberService memberService = applicationContext.getBean("memberService", MemberService.class);
// MemberService memberService = appConfig.memberService();

빈 등록 로그

02:16:40.518 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'appConfig'
02:16:40.530 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'memberService'

스프링 컨테이너 내부엔 스프링 빈 저장소이고 생성할 땐 구성 정보를 지정해야 한다. (AppConfig)
스프링 빈 저장소는 <빈 이름, 빈 객체>로 구성되어 있고 각 메서드 이름과 반환 객체를 의미한다.
(memberService, new MemoryMemberService())

빈 생성과 의존관계 주입하는 단계가 나누어져 있다.

스프링 빈 이란?

스프링 컨테이너에 등록되고 관리되는 객체를 의미하고 getBean() 으로 가져올 수 있다.

컨텍스트에 등록된 빈 목록 출력

AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = ac.getBean(beanDefinitionName);
            System.out.println(beanDefinitionName+" "+bean);
        }
        
// appConfig hello.core.AppConfig$$EnhancerBySpringCGLIB$$511159a3@5be49b60
// memberService hello.core.member.MemberServiceImpl@19e7a160
profile
기록

0개의 댓글