前面我们在讲到工厂模式的时候,提到了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
本文介绍了Spring框架中的Bean工厂及IOC概念,展示了如何通过XML配置文件定义Bean,并通过示例代码演示了如何创建和使用这些Bean。
1083

被折叠的 条评论
为什么被折叠?



