본문 바로가기
JAVA/Spring

Spring예제 - bean컨테이너 사용

by 설총이 2018. 9. 5.


[applicationContext.xml]



1
2
3
4
5
6
7
8
9
10
11
<!-- bean : 컨테이너가 객체 생성 -->
<bean name="writeArticleService"
    class="spring.chap01.WriteArticleServiceImpl">
    <constructor-arg>
        <ref bean="articleDao" />
    </constructor-arg>
</bean>
 
<bean name="articleDao" class="spring.chap01.MySQLArticleDao">
 
</bean>
cs



bean 컨테이너가 두개의 bean 객체를 생성해서 정보를 담아 놓는다.



[main.java]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
        Resource resource = new ClassPathResource("applicationContext.xml");
        // 1. src폴더안에있는 applicationContext.xml을 resource로 가져옴.
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        // 2. BeanFactory : 스프링 컨테이너. 가장 큰 조상객체라 사용 권장X 
        //--> BeanFactory를 구현받고잇는 application으로 할것임

        
        WriteArticleService articleService = (WriteArticleService) beanFactory.getBean("writeArticleService");
        // 3. beanFactory에는 위에 ClassPath로 가져온 xml에서의 bean으로 저장된것들을 가져옴.
        // => 이 시점에서 beanFactory에는 두개의 bean 객체가 저장된다. 그것을 get!!
        
        // 4. applicationContext.xml에 저장된 bean은 writeArticleService라는 name으로 저장되어 있지만,
        // 사용하는 class는 상속받고있는 spring.chap01.WriteArticleServiceImpl 이다.
        
        articleService.write(new Article());
        // 5. 그래서 articleService.write로 사용하는 메서드는 articleService가 아니라
        //구현받은 WriteArticleServiceImpl가 된다.
        
        //6. 조상타입의 '변수'로 구현받고있는 자손타입의 메서드를 실행함을 기억.
cs



2번에서 beanFactory가 객체를 만들면서 xml파일을 읽어들여서 객체화한다.

여기서 xml에는 두개의 bean객체가 로딩된것을 객체화를 함.


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

Spring예제 - setter방식  (2) 2018.09.06
Spring예제 - bean과 aop혼합사용  (0) 2018.09.05
Spring(maven / gradle) 설치, 순서  (0) 2018.09.05
JsonObject와 JsonArray 사용  (0) 2018.08.17
ContextPath/URI/URL/SErvletPath/RealPath 정리  (0) 2018.08.01