Java Factory概念学习第四课(BeanFactory)
beanFactory
今天引入Spring自带的factory即BeanFactory
先模拟beanFactory的工作原理:
public interface Moveable {
void run();
}
public class Car implements Moveable{
public void run() {
System.out.println("奔跑中。。。。");
}
}
模拟配置文件springtest.properties
VehicleType=com.beanfactory.Car
然后Test读取数据:
public class Test {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.load(Test.class.getClassLoader().
getResourceAsStream("com/beanfactory/springtest.properties"));
String vehicleType = p.getProperty("VehicleType");
System.out.println(vehicleType);
Moveable m = (Moveable)Class.forName(vehicleType).newInstance();
m.run();
}
}
接下来看Spring究竟是怎么实现的,导包的过程省略:
在之前的基础上再加入一个Train类:
public class Train implements Moveable {
@Override
public void run() {
System.out.println("火车况且况且");
}
}
此时要将之前我们模拟spring的配置文件替换为spring的标准配置文件:
先编写标准的spring xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="v" class="com.springfactory.Train">
</bean>
</beans>
之后改写Test类,启用spring的beanfactory方法:
public class Test {
public static void main(String[] args) throws Exception {
BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml");
Object object = bf.getBean("v");
Moveable m = (Moveable)object;
m.run();
}
}
以上就是初步的spring的BeanFactory