spring-加载入口
程序员文章站
2024-01-29 12:24:22
...
spring-加载入口
版本:5.2.8
ContextLoaderListener
实现了ServletContextListener接口,可以在ServletContext创建时执行contextInitialized方法;
继承了ContextLoader类,主要的业务逻辑写在这个父类中,此处没有放到一个类中写,做到了分离;
public void contextInitialized(ServletContextEvent event) {
// 调用父类方法
initWebApplicationContext(event.getServletContext());
}
ContextLoader
初始化
类加载的时候执行的初始化,加载当前类路径的一个名为ContextLoader.properties文件到defaultStrategies里;
private static final Properties defaultStrategies;
static {
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
ContextLoader.properties文件内容,其实就是配置WebApplicationContext的实现类;
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
initWebApplicationContext()
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
// 判断如果servletContext中已经有该WebApplicationContext,则说明已经加载了
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// 构建WebApplicationContext
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
// 由上一步可以知道是ConfigurableWebApplicationContext的实现类
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
// 现在是不活跃的状态
if (!cwac.isActive()) {
// 默认是空的
if (cwac.getParent() == null) {
// 此处返回的也是null
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
// 实际的加载处理在这个方法中
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 把这个context存到servletContext中,与之前的先判断是否存在相对应
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
createWebApplicationContext()
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 决定使用用户配置的实现类还是ContextLoader.properties中配置的实现类
Class<?> contextClass = determineContextClass(sc);
// 当前的contextClass是不是ConfigurableWebApplicationContext的实现类,通过下图的类结构能判断出是这个接口的实现类
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
// 这里返回了一个ConfigurableWebApplicationContext类型的WebApplicationContext
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
determineContextClass()
protected Class<?> determineContextClass(ServletContext servletContext) {
// 从web.xml中查找是否在<context-param>标签的<param-name>中配置了contextClass,一般不配置
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
// 此处就是从ContextLoader.properties文件中获取的具体实现类
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
configureAndRefreshWebApplicationContext()
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
// 获取在web.xml中配置的spring配置文件名
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
// 加载bean
wac.refresh();
}