如果说BeanFactory是Spring的心脏,那么ApplicationContext就是完整的身躯了。ApplicationContext由BeanFactory派生而来,提供了更多面向实际应用的功能。在BeanFactory中,很多功能需要以编程的方式实现,而在ApplicationContext中则可以通过配置的方式实现。
一、ApplicationContext
ApplicationContext的主要实现类是ClassPathXmlApplication和FileSystemXmlApplicationContext,前者默认从类路径中加载配置文件,后者默认从文件系统中装载配置文件。
与BeanFactory初始化相似,ApplicationContext的初始化也很简单,如果配置文件在类路径下,用户可以优先使用ClassPathXmlApplication实现类:
1、ClassPathXmlApplication:从类路径中加载配置文件
(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)Bean配置文件——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.ClassPathXmlApplicationContext;
/**
*
* @author huamanxi
* ClassPathXmlApplicationContext类
*/
public class ClassPath {
@Test
public void testClassPath(){
ApplicationContext ac=new ClassPathXmlApplicationContext("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");
}
}
注意:别忘了
log4j.properties文件
运行结果:
init ApplicationContext
brand:宝马 color:黑色 maxSpeed:200
Car bean is ready for use