FrameWork/Spring

컨테이너에 빈 등록 및 조회

jheaon 2024. 5. 27. 22:02

 

오늘은 스프링 컨테이너에 빈 등록, 조회를 하는 방법에 대해 알아보자.


 

컨테이너에 빈 등록하기

스프링 컨테이너에 빈을 등록하는 방법은 2가지가 있다. 

  • @Bean을 통해 직접 등록하는 방법
@Configuration
public class AppConfig {
    @Bean
    public MemberRepository memberRepository(){
        return new MemoryMemberRepository();
    }
}

 

@Configuration 구성 정보에 @Bean 어노테이션을 통해 스프링 컨테이너에 직접 빈을 등록할 수 있다. 빈 객체로 등록하고 싶은 메서드 위에 @Bean 어노테이션을 추가해 사용한다. 

 

  • @ComponentScan을 이용하여 자동으로 빈 등록하는 방법
@Configuration
@ComponentScan
public class AppConfig {
...
}

 

우선 AppConfig에 @ComponetScan 어노테이션을 추가한다. 

@Component
public class MemoryMemberRepository implements MemberRepository {
...
}

 

그리고 빈 객체로 등록하고 싶은 클래스에 @Component 어노테이션을 추가한다. 스프링은 @Configuration 어노테이션을 가진 클래스를 먼저 찾은 뒤, @ComponentScan이 있다면, @Component 어노테이션이 있는 클래스를 찾아 스프링 컨테이너에 빈으로 등록한다. 

 

 

 

 

컨테이너에 등록된 빈 조회하기

컨테이너에 등록된 빈을 조회하기 위해서는 AnnotationConfigApplicationContext() 객체에서 접근해서 정보를 가져올 수 있다. 

AnnotationConfigApplicationContext ac = new AnnotationCOnfigApplicationContext(AppConfig.class);

// 빈 전체 이름을 String 배열로 반환받음
// 배열을 순회하면서 출력
String[] beanDefinitionNames = ac.getBeanDefinitionNames();
Arrays.stream(beanDefinitionNames).forEach(System.out::println);

// 특정 빈을 조회하고 싶다면, getBean(빈 이름, 클래스)로 조회가능
MemberService memberService = ac.getBean("memberSerVice", MemberService.class);

 

  • ac.getBeanDefinitionNames() : 스프링에 등록된 모든 빈 이름을 조회한다. 
  • ac.getBean(타입) 또는 ac.getBean(빈이름, 타입): 빈 객체(인스턴스)를 조회한다.
  • 참고로 부모 타입으로 조회를 하면 자식 타입도 함께 조회된다. (Object 타입으로 조회하면, 모든 스프링 빈을 조회한다.)

'FrameWork > Spring' 카테고리의 다른 글

ComponentScan  (0) 2024.05.30
싱글톤 패턴과 컨테이너  (0) 2024.05.28
IoC, DI 컨테이너  (0) 2024.05.27
Thymeleaf  (0) 2024.05.21
JDBC (내용 추가 예정)  (0) 2024.05.20

'FrameWork/Spring'의 다른글

  • 현재글 컨테이너에 빈 등록 및 조회

관련글