如果需要使运行速度更快,在创建一个spring的ioc工厂时往往会使用ApplicationContext而不是BeanFactory :
ApplicationContext ioc = new ClassPathXmlApplicationContext("config/applicationContext.xml");
在读了其在spring的开源代码后在此总结一下我的收获。
其中ApplicationContext是一个接口,它继承了EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver等接口:
它定义的方法有:
Stirng getId(); //获得application context特有的Id,如果没有的话会返回null
String getApplicationName(); //获得当前context所属的应用的名字
String getDisplayName(); //获得context默认的名称
long getStartupDate(); //当context第一次被加载时获得时间戳
ApplicationContext getParent(); //返回applicationContext的父类,有层次关系
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
在New一个容器时此处调用的方法源代码为:
/**
*创建一个新的ClassPathXmlApplicationContext,从被给与的xml文件加载定义好的对象,并刷新context
*/
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
其中this调用自身的方法:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent); //其中super()方法根据参数ApplicationContext parent从被给予的父类的context创建一个新的AbstractXmlApplicationContext
setConfigLocations(configLocations);
if (refresh) {
refresh(); //更新已有的单例模式
}
}
其中 setConfigLocations()来自抽象类AbstractRefreshableConfigApplicationContext中的方法:
/**
*为application context 配置路径(config locations)
*/
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
/**
*public static void noNullElements(Object[] array, String message) {
* if (array != null) {
* for (Object element : array) {
* if (element == null) {
* throw new IllegalArgumentException(message); //如果array不为null,遍历array[]数组中的元素,如果存在元素为null,则抛出异常,异常信息为参数message
* }
* }
* }
* }
*/
this.configLocations = new String[locations.length]; //AbstractRefreshableConfigApplicationContext 存在的(private String[] configLocations) 一个String数组,此处根据参数地址location的长度来设置configLocations
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim(); //将原有的路径进行替换成所传入的location参数
}
}
else {
this.configLocations = null;
}
}