Post

Spring Container and Bean with configuration class(1)

✅ Spring Container and Bean

  • ✔️ Spring container: manage object creation and DI and overall flow of the application
    • Spring container 🟰 ApplicationContext
  • ✔️ Bean: Object that is added to Spring container

    • Java object that is managed by the Spring container
    • special object that Spring takes care for you - creates, manages dependencies, manage life cycle
  • add annotation @Configuration
  • Spring container will use @Configuration as DI information/metadata

  • Spring container wil call all methods with @Bean and add it to spring container
  • only creates the @Bean once

💡 How to add Bean

  • @Bean등록하는 방법
  • 1️⃣ manual bean configuration with @Configuration
  • 2️⃣ component scan with @ComponentScan, @Autowired
  • 이 게시글에서는 1️⃣번 방법에 대해 설명한다

  • 1️⃣ Create Spring container @Configuration class
  • Spring does not magically know what to add as bean ➡️ add what you want to add as bean in @Configuration class
1
2
3
@Configuration
public class AppConfig {
}
1
2
3
4
5
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

//get memberService from AppCofig called by Spring container
MemberService memberService = applicationContext.getBean("memberService", MemberService.class);

Image

  • 2️⃣ Add beans to Spring container
  • add @Bean as Spring bean to Spring container
1
2
3
4
5
6
7
@Configuration
public class AppConfig {

    @Bean
    public MemberService memberService(){
        return new MemberServiceImpl(memberRepository());
    }

Image

✅ Get beans in test code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

//print all beans
String[] beanDefinitionNames = ac.getBeanDefinitionNames();

//find bean by name
MemberService memberService = ac.getBean("memberService", MemberService.class);

//find bean by type
//이 때 type아래 여러개 있으면 에러
MemberService memberService = ac.getBean(MemberService.class);

//type아래 있는 모든 bean 다 find
Map<String, MemberRepository> beansOfType = ac.getBeansOfType(MemberRepository.class);
  • 부모 type으로 bean을 찾아오면 부모 ➕ 그 자식들도 모두 찾아온다
  • bean not found: NoSuchBeanDefinitionException
  • 하나의 클래스 안에 bean이 여러개: NoUniqueBeanDefinitionException

✅ Bean Factory

ApplicationContext implements ➡️ Bean Factory(interface)

  • ✔️ Bean Factory: manage and find beans

    • getBean(), getBeansOfType() 메소드 등 모두 Bean Factory의 기능이다
  • Spring container인 ApplicationContextBean Factory를 상속받아
  • Bean Factory의 기능들에 자신의 기능들을 추가해서 Spring container를 구현한다.
This post is licensed under CC BY 4.0 by the author.