• Spring ApplicationContext(二)环境准备


    Spring ApplicationContext(二)环境准备

    Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html)

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

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

    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() 也因为没有需要验证的属性而没有做任何处理。其实这这都是因为没有彻底理解才会这么说,这个函数如果用好了作用还是挺大的。那么,该怎么用呢?我们先探索下各个函数的作用。

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

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

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

    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 的环境变量,那么将抛出异常。当然我们还需要在使用的时候替换掉原有的

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

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

  • 相关阅读:
    真的要努力了
    实事求是
    要努力了
    新征程,新目标
    真的要放弃了吗
    集中力量 主攻文科
    May the force be with me.
    记录级排名
    Android开发过程中git、repo、adb、grep等指令的使用
    Ubuntu环境变量设置
  • 原文地址:https://www.cnblogs.com/binarylei/p/10423495.html
Copyright © 2020-2023  润新知