核心配置文件入口类的执行顺序
该类实现了两个接口: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");
}
}