반응형

Spring BeanFactory Container



(원문 위치 : http://www.tutorialspoint.com/spring/spring_beanfactory_container.htm )


Spring으로 바로 사용할 수 있게 공급하는 BeanFactory interface의 구현은 여러가지가 있다. 가장 일반적인 BeanFactory 구현은 XmlBeanFactory class이다. 이 container는 XML file에서 설정 metadata를 읽고 완전하게 설전된 system 혹은 application을 생성하기 위해 리를 사용한다.


BeanFactory는 보통 Applet기반이나 모바일 기기같은 제한된 리소스가 제한된 곳에서 사용된다. 따라서 특별한 이유가 없다면 ApplicationContext를 사용해라.


Example:

- [003] HelloWorld Example 절차를 따라 프로젝트를 생성한다.
  . package : com.tutorialspoint
  . project : 02.SpringExample    (<- 이건 이 사이트의 예제가 모두 SpringExample를 사용하기 때문임)

- [003] HelloWorld Example의 소스코드와 MainApp.java를 제외하고는 동일하다.
  

 HelloWorld.java:

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

MainApp.java:

package com.tutorialspoint;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class MainApp {
   public static void main(String[] args) {
      XmlBeanFactory factory = new XmlBeanFactory
                             (new ClassPathResource("Beans.xml"));

      HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
      obj.getMessage();
   }
}

main program에 아래와 같은 두가지 중요한 점이 있다.

XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));

 : Factory bean을 생성하기 위한 XmlBeanFactory() framework API를 사용해 factory 객체를 생성하고 CLASSPATH내 가능한 bean 설정파일을 로드하기 위해 ClassPathResource() API를 사용. XmlBeanFactory() API는 설정파일에서 언급되는 모든 bean 객체를 생성하고 초기화에 관여한다.

      HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
 : 생성된 bean factory 객체의 getBean()을 이용하여 필요한 Bean을 가져온다. 이 함수는 결국 실제 객체가 캐스팅되어질 수 있는 generic 객체를 return하기 위해 bean ID를 사용한다.

Beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

실행 결과는 아래와 같다.

Your Message : Hello World!




반응형

+ Recent posts