컴포넌트 스캔(ComponentScan)과 빈(Bean) 설정

2022. 8. 15. 17:46JAVA/Spring

스프링 빈 설정 파일 구현

자바 설정 파일을 이용하여 빈 객체를 생성하는 방법에는 두가지 방법이 있습니다.

  • @Bean 어노테이션을 이용한 빈 설정
  • @ComponentScan 어노테이션을 이용한 빈 설정

 

java 파일에 빈 설정

1. @Bean 어노테이션을 이용한 빈 설정

@Configuration
public class ApplicationConfig {

    @Bean
    public BookService bookService(){
        return new BookService(bookRepository());
    }

    @Bean
    public BookRepository bookRepository(){
        return new BookRepository();
    }

}
  • 설정 파일 클래스를 생성한 다음 @Configuration 애노테이션을 적용합니다.
  • 빈 객체로 등록할 객체를 대상으로 빈 객체 생성 메서드를 정의합니다.
  • BookService 객체는 BookRepository 객체를 의존합니다. 따라서 빈 객체 생성 과정에서 BookService와 BookRepository 객체간의 의존 관계를 주입합니다.

 

테스트 코드

@Test
	public void givenAnnotationConfigApplicationContextUsingBeanAnnotation_whenGetBookService_thenBookRepositoryIsNotNull() throws Exception{
		//given
		ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);

		//when
		String[] beanDefinitionNames = context.getBeanDefinitionNames();
		BookService bookService = (BookService) context.getBean("bookService");

		//then
		assertThat(beanDefinitionNames).contains("bookService", "bookRepository");
		assertThat(bookService.getBookRepository()).isNotNull();
	}

 

2.2 @ComponentScan 어노테이션을 이용한 빈 설정

 

@Configuration
@ComponentScan(basePackageClasses = SpringBasicApplication.class)
public class ApplicationConfig2 {

}
  • ComponentScan을 적용하기 위해서 @Configuration 애노테이션을 적용합니다.
  • ComponentScan 속성으로 basePackageClasses = SpringBasicApplication.class 를 설정하면 SpringBasicApplication.class 위치를 기준으로 현재 위치와 서브 디렉토리를 탐색하여 빈 객체를 생성합니다.

 

 

테스트코드

@Test
	public void givenAnnotationConfigApplicationContextUsingComponentAnnotation_whenGetBookService_thenBookRepositoryIsNotNull() throws Exception{
		//given
		ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig2.class);

		//when
		String[] beanDefinitionNames = context.getBeanDefinitionNames();
		BookService bookService = (BookService) context.getBean("bookService");

		//then
		assertThat(beanDefinitionNames).contains("bookService", "bookRepository");
		assertThat(bookService.getBookRepository()).isNotNull();
	}

 

References

source code : https://github.com/yonghwankim-dev/spring_study
[인프런] 스프링 프레임워크 핵심 기술