Spring ApplicationContext(二)环境准备

Spring ApplicationContext(二)环境准备

Spring 系列目录(http://www.javashuo.com/article/p-kqecupyl-bm.html)html

本节介绍容器初始化的第一步:环境准备工做。java

prepareRefresh 函数主要是作些准备工做,例如对系统属性及环境变量的初始化及验证。spring

protected void prepareRefresh() {
    this.startupDate = System.currentTimeMillis();
    this.closed.set(false);
    this.active.set(true);

    // 1. 留给子类覆盖,如添加要验证的属性
    initPropertySources();

    // 2. 验证须要的属性文件是否都已经放入环境中
    getEnvironment().validateRequiredProperties();

    // 3. 若是多播器还未初始化完成,就将早期发布的事件统一放到集合中,等多播器初始化完成后再发布事件
    this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

网上有人说其实这个函数没什么用,由于最后两句代码才是最为关键的,可是却没有什么逻辑处理,initPropertySources 是空的,没有任何逻辑,而 getEnvironment().validateRequiredProperties() 也由于没有须要验证的属性而没有作任何处理。其实这这都是由于没有完全理解才会这么说,这个函数若是用好了做用仍是挺大的。那么,该怎么用呢?咱们先探索下各个函数的做用。app

(1) initPropertySources 正符合 Spring 的开放式结构设计,给用户最大扩展 Spring 的能力。用户能够根据自身的须要重写 initPropertySources 方法,并在方法中进行个性化的属性处理及设置。ide

(2) validateRequiredProperties 则是对属性进行验证,那么如何验证呢?咱们举个融合两句代码的小例子来帮助你们理解。函数

假如如今有这样一个需求,工程在运行过程当中用到的某个设置(例如 VAR)是从系统环境变量中取得的,而若是用户没有在系统环境变量中配置这个参数,那么工程可能不会工做。这一要求可能会有各类各样的解决办法,固然,在 Spring 中能够这样作,你能够直接修改 Spring 的源码,例如修改 ClassPathXmlApplicationContext。固然,最好的办法仍是对源码进行扩展,咱们能够自定义类:ui

public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {

    public MyClassPathXmlApplicationContext(String configLocations) throws BeansException {
        super(configLocations);
    }

    public MyClassPathXmlApplicationContext(String path, Class<?> clazz) throws BeansException {
        super(path, clazz);
    }

    @Override
    protected void initPropertySources() {
        // 添加验证要求
        getEnvironment().setRequiredProperties("VAR");
    }
}

咱们自定义了继承自 ClassPathXmlApplicationContext 的 MyClassPathXmlApplicationContext,并重写了 initPropertySources 方法,在方法中添加了咱们的个性化需求,那么在验证的时候也就是程序走到 getEnvironment().validateRequiredProperties() 代码的时候,若是系统并无檢测到对应 VAR 的环境变量,那么将抛出异常。固然咱们还须要在使用的时候替换掉原有的this

public static void main(String[] args) {
    ApplicationContext context = new MyClassPathXmlApplicationContext(
            "spring-context-test.xml", Main.class);
    MyTestBean myTestBean = (MyTestBean) context.getBean("myTestBean");
}

天天用心记录一点点。内容也许不重要,但习惯很重要!设计

相关文章
相关标签/搜索