2、FileSystemXmlApplication:从文件系统中装载配置文件
(1)实现类——Car.java文件
public class Car {
private String brand;
private String color;
private int maxSpeed;
public Car(){
}
public Car(String brand, String color, int maxSpeed) {
super();
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "brand:"+brand+" color:"+color+" maxSpeed:"+maxSpeed;
}
}
(2)配置文件——beans.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="car1" class="com.bean.Car"
p:brand="宝马"
p:color="黑色"
p:maxSpeed="200"/>
</beans>
(3)Spring IoC容器
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* @author huamanxi
* FileSystemXmlApplicationContext类
*/
public class FileSystem {
@Test
public void testFileSystem(){
ApplicationContext ac=new FileSystemXmlApplicationContext("E://MYeclipse//myeclipse1//ApplicationContext//src//com//bean//beanfactory//beans.xml");
System.out.println("init ApplicationContext");
Car car=(Car) ac.getBean("car1");
System.out.println(car);
System.out.println("Car bean is ready for use");
}
}
运行结果:
init ApplicationContext
brand:宝马 color:黑色 maxSpeed:200
Car bean is ready for use
由运行结果可以看出,两种加载配置文件的方式得到的结果完全相同。
ApplicationContext与BeanFactory初始化的区别:
BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean时才实例化目标Bean
而ApplicationContext则在初始化应用上下文时就实例化所有单实例的Bean。
因此ApplicationContext的初始化时间会比BeanFactory稍微长一点。