前面我們在講到工廠模式的時候,提到了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接口的子類:
Car和Train
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,它的id爲v,然後它的class是com.bjsxt.spring.factory.Train
本文word文檔下載:
http://wenku.baidu.com/view/69f94e80d0d233d4b14e6970.html?st=1