Spring IoC示例

          Posted on 2009-06-17 13:18 eric_xu 閱讀(283) 評(píng)論(0)  編輯  收藏 所屬分類: J2EE
          一個(gè)IoC的Demo程序
          beans-config.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-2.5.xsd">
              
          <bean id="helloBean" class="sjtu.rfid.HelloBean">
                  
          <property name="helloWord">
                      
          <value>Hello! Eric!</value>
                  
          </property>
              
          </bean>
          </beans>
          SpringDemo.java
          package sjtu.rfid;

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

          public class SpringDemo {
              
          public static void main(String[] args){
                  ClassPathResource resource 
          = new ClassPathResource("beans-config.xml");
                  BeanFactory factory 
          = new XmlBeanFactory(resource);
                  HelloBean hello 
          = (HelloBean) factory.getBean("helloBean");
                  System.out.println(hello.getHelloWord());
              }
          }
          ClassPathResource在指定classpath中尋找配置文件
          resource為接口,有
          ClassPathResource,F(xiàn)ileSystemResource,InputStreamResource,ServletContextRescource或UrlResource等,都可作為XmlBeanFactory構(gòu)造函數(shù)的參數(shù),這兒為XML。BeanFactory管理不同形態(tài)的物件,可以是XML。

          org.springframework.beans.factory.BeanFactorySpring IoC容器的實(shí)際代表者,IoC容器負(fù)責(zé)容納此前所描述的Bean,并對(duì)Bean進(jìn)行管理。BeanFactoryIoC容器的核心接口,加載配置文件的方法:

          1.Resource resource = new FileSystemResource("beans-config.xml");

          2.ApplicationContext context = new ClassPathXmlApplicationContext(

                             new String[] {"ApplicationContext.xml", "ApplicationContext2.xml"});

          BeanFactory factory = context;


          HelloBean.java
          package sjtu.rfid;

          public class HelloBean {
              
          private String HelloWord;

              
          public String getHelloWord() {
                  
          return HelloWord;
              }

              
          public void setHelloWord(String helloWord) {
                  HelloWord 
          = helloWord;
              }
          }

          posts - 37, comments - 5, trackbacks - 0, articles - 0

          Copyright © eric_xu

          主站蜘蛛池模板: 河源市| 仪征市| 潜山县| 旺苍县| 保山市| 肃宁县| 宁陵县| 长顺县| 嵩明县| 密云县| 怀柔区| 通榆县| 辽中县| 芜湖县| 肥西县| 章丘市| 安丘市| 周宁县| 遂昌县| 陈巴尔虎旗| 界首市| 温州市| 静安区| 万荣县| 西乌| 沅江市| 永嘉县| 剑河县| 江西省| 西宁市| 化州市| 五原县| 平南县| 宁安市| 新化县| 尉犁县| 和静县| 徐水县| 青田县| 舒兰市| 绥芬河市|