spring-ApplicationContext

若是须要使运行速度更快,在建立一个spring的ioc工厂时每每会使用ApplicationContext而不是BeanFactory :spring

ApplicationContext ioc = new ClassPathXmlApplicationContext("config/applicationContext.xml");数组

在读了其在spring的开源代码后在此总结一下个人收获。app

其中ApplicationContext是一个接口,它继承了EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver等接口:this

它定义的方法有:xml

Stirng getId();  //得到application context特有的Id,若是没有的话会返回null对象

String getApplicationName(); //得到当前context所属的应用的名字继承

String getDisplayName();  //得到context默认的名称接口

long getStartupDate();  //当context第一次被加载时得到时间戳element

ApplicationContext getParent(); //返回applicationContext的父类,有层次关系get

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;        }    }

相关文章
相关标签/搜索