Spring Framework

스프링(3) - 빈 팩토리

다미르 2019. 3. 22. 15:43

스프링(3) - 빈 팩토리


빈을 따라가는 여행 그 세 번째.

앞에 어쩌다보니 이상한 소리만 엄청 길고,

실제로 된 거라고는 ... 빈 def 객체와 그 것을 생성하는 통합(?)클래스 빌더 뿐이 었다.

이번엔 정말로 빈을 생성해보자.


실제로 이렇게 빈을 생성하는 경우는 ... 없을 것 같지만

빌더와 팩토리가 드러나는 샘플같아서 작성해본다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class BeanDefinitonBuilderEx {
 
    private static class SampleBean {
        private String property;
 
        public void setProperty(String property) {
            this.property = property;
        }
 
        public void doSomething() {
            System.out.println("do doSomething of SampleBean");
        }
    }
 
    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
 
        BeanDefinitonBuilder builder = BeanDefinitonBuilder.rootBeanDefinition(SampleBean.class)
                                                            .addPropertyValue("property""property value");
 
        beanFactory.registerBeanDefinition("sampleBean", builder.getDefinition());
 
        SampleBean sampleBean = beanFactory.getBean();
        sampleBean.doSomething();// result might be do doSomething of SampleBean
    }
}
cs

내가 만든 SampleBean 객체는 필드변수 property와 doSomething() 메서드로 구성되어 있다.이를 빈으로 등록하기 위해서 1) 빌더를 통해서 RootBeanDefinition 객체를 호출하여2) Bean의 property 설정을 한 뒤3) BeanFactory 인터페이스를 구현한 DefaultListableBeanFactory 객체를 통해 등록하고4) getBean() 메서드를 통해서 생성된 빈의 참조변수를 return 받아5) doSomthing() 메서드를 호출하였다.

스프링의 다른 모듈들이 모두 이런 방식으로 빈을 생성하지는 않을 것이다.

빌더 > 팩토리 > 빈 이런 식의 인스턴스 방식은 어느정도 일치하는 것 같다.

.. 이걸 왜하고 있는지 모르겠네 이제