核心配置文件入口类的执行顺序

核心配置文件入口类的执行顺序

该类实现了两个接口:ApplicationListener<ContextRefreshedEvent>,ServletContextAware

执行顺序如下:

(1)依赖资源的注入

比如使用注解@Resource的setter方法

(2)实现接口ServletContextAware的setServletContext 方法

(3)onApplicationEvent方法

 

核心配置类如下:

package com.xx.config;


import com.xxx.util.SpringMVCUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

/**
 * Created by 黄威 on 9/19/16.<br >
 *     读取配置文件的核心类,是获取properties参数的唯一入口<br >
 *         执行顺序<br>
 */
@Configuration
public class EnvironmentBean implements ApplicationListener<ContextRefreshedEvent>,ServletContextAware {
    @Autowired
    ConfigurableEnvironment env;
    private MutablePropertySources sources;
    private ServletContext servletContext;

    public String getProperty(String key) {
        if(env.containsProperty(key)){
            return env.getProperty(key);
        }
        return null;
    }
    /***
     * Spring容器加载完成触发,可用于初始化环境,准备测试数据、加载一些数据到内存
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("add Sources to env ...");
        SpringMVCUtil.addCustomPropertySources(this.sources, env);
        System.out.println("add Sources to env completely");
        API.init(this);
        Const.init(this);
        
    }
    public MutablePropertySources getSources() {
        return sources;
    }

    @Resource
    public void setSources(MutablePropertySources sources2) {
        System.out.println("setSources");
        this.sources = sources2;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext=servletContext;
        System.out.println("setServletContext");
        this.servletContext.setAttribute("passporttest", "www.abc.com");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值