设计模式之4.1 Spring入门初步之Spring bean工厂

来源:互联网 发布:python退出程序命令 编辑:程序博客网 时间:2024/06/06 00:51

前面我们在讲到工厂模式的时候,提到了spring的bean工厂。这里详细说明一下:

 


http://wenku.baidu.com/view/69f94e80d0d233d4b14e6970.html?st=1本文word格式下载:本文word格式下载:

Spring的bean容器,bean工厂,也叫IOC(Inverseof Control),是面向接口编程,面向抽象编程。

 

Spring的使用入门:

首先也有moveable接口:

package com.bjsxt.spring.factory;

 

publicinterface Moveable {

    void run();

}

 

当然也有实现moveable接口的子类:

CarTrain

 

package com.bjsxt.spring.factory;

 

 

publicclass Carimplements Moveable{

   

   

   

    publicvoid run() {

       System.out.println("冒着烟奔跑中car.......");

    }

}

 

package com.bjsxt.spring.factory;

 

publicclass Trainimplements Moveable{

 

    @Override

    publicvoid run() {

       System.out.println("小火车呜呜呜");

    }

   

}

 

关键是在test(使用者)里面:

package com.bjsxt.spring.factory;

 

import java.io.IOException;

 

import org.springframework.beans.factory.BeanFactory;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

//以前我们都是通过properties文件来读取信息,得到这个类的名字。然后通过反射,得到这个类的对象。

publicclass Test {

 

    /**

     *@paramargs

     *@throwsIOException

     */

    publicstaticvoid main(String[] args)throws Exception {

       //通过xml文件来读取信息

       //因为使用了xml所以读取的方式不一样。

       BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml");

       Object o = f.getBean("v");

       Moveable m = (Moveable)o;

       m.run();

    }

 

}

 

 

再来看看xml文件当中的信息:

 

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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">

 

  <beanid="v"class="com.bjsxt.spring.factory.Train">

  </bean>

 

  <!-- //v=com.bjsxt.spring.factory.Car  -->

 

 

</beans>

 

很简单,有个bean,它的idv,然后它的classcom.bjsxt.spring.factory.Train

 

本文word文档下载:

http://wenku.baidu.com/view/69f94e80d0d233d4b14e6970.html?st=1

原创粉丝点击