启动Spring项目详细过程(小结)

 更新时间:2019年11月08日 09:48:01   作者:君寞傲  
这篇文章主要介绍了启动Spring项目详细过程(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、Spring 项目放到web项目容器中(Tomcat、Jetty、JBoss)

本文以通用的Tomcat为例

2、项目容器启动时需要加载读取web.xml配置文件

如下图:

3、容器首先会去读取web.xml配置文件中的两个节点:<listener> </listener>和<context-param> </context-param>

说明:

tomcat在启动web容器的时候会启动一个叫ServletContextListener的监听器,每当在web容器中有ServletContextListener这个接口被实例化的时候,web容器会通知ServletContextListener被实例的对象去执行其contextInitialized()的方法进行相应的业务处理;

而spring框架在设计的过程中ContextLoadListener这个类实现了ServletContextListener这个接口,因此每当有ContextLoadListener这个类被实例化的时候,web容器会通知Spring执行contextInitialized()这个方法,从而进行spring容器的启动与创建的过程中;

4、ContextLoaderListener中的contextInitialized()进行了spring容器的启动配置,调用initWebApplicationContext初始化spring容器;

@Override
public void contextInitialized(ServletContextEvent event) {
  initWebApplicationContext(event.getServletContext());
}
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  //Spring 启动的句柄,spring容器开始启动的根目录
  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!");
  } else {
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if(logger.isInfoEnabled()) {
      logger.info("Root WebApplicationContext: initialization started");
    }
 
    long startTime = System.currentTimeMillis();
 
    try {
      //处理spring容器是否已经创建(只创建没有创建spring的各个bean)
      if(this.context == null) {
        this.context = this.createWebApplicationContext(servletContext);
      }
 
      if(this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)this.context;
        if(!cwac.isActive()) {
          if(cwac.getParent() == null) {
            ApplicationContext parent = this.loadParentContext(servletContext);
            cwac.setParent(parent);
          }
 
          //Spring容器创建完成后,加载spring容器的各个组件
          this.configureAndRefreshWebApplicationContext(cwac, 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.isDebugEnabled()) {
        logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
      }
 
      if(logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
      }
 
      return this.context;
    } catch (RuntimeException var8) {
      logger.error("Context initialization failed", var8);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, var8);
      throw var8;
    } catch (Error var9) {
      logger.error("Context initialization failed", var9);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, var9);
      throw var9;
    }
  }
}

5、spring容器创建完成后,准备开始实例化加载bean,Spring容器创建完成后,准备向spring容器中加载bean 使用configureAndRefreshWebApplicationContext(cwac, servletContext); 完成bean的加载;

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			// The application context id is still set to its original default value
			// -> assign a more useful id based on available information
			String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
			if (idParam != null) {
				wac.setId(idParam);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}
 
		wac.setServletContext(sc);
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}
 
		// The wac environment's #initPropertySources will be called in any case when the context
		// is refreshed; do it eagerly here to ensure servlet property sources are in place for
		// use in any post-processing or initialization that occurs below prior to #refresh
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
		}
 
		customizeContext(sc, wac);
		wac.refresh();
	}

说明:

configureAndRefreshWebApplicationContext中加载spring的配置文件,即web.xml中读取<context-param></context-param>中加载到Spring的配置文件,即:classpath:/config/applicationContext.xml;

通过以下代码加载spring配置

public class Application{
 public static void main(String[] args) {
  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/context.xml");
  ctx.start();
 }
}

此处略过如何调用DefaultResourceLoader

顶级接口ResourceLoader仅提供了一个getResource(String location)方法,可以根据一个资源地址加载资源文件,资源地址的表达式可以是以下几种:

--1. classpath:前缀开头的表达式,例如: classpath:smart-context.xml

--2.“/”开头的表达式,例如:/WEB-INF/classes/smart-context.xml

--3. 非“/”开头的表达,例如:WEB-INF/classes/smart-context.xml

--4. url协议,例如:file:/D:/ALANWANG-AIA/Horse-workspace/chapter3/target/classes/smart-context.xml

Spring提供了实现类DefaultResourceLoader,DefaultResourceLoader在实现了以上列举的功能基础上,还为开发者提供了自定义扩展接口ProtocolResolver,开发者可实现该接口定制个性化资源表达式,代码如下:

@Override
	public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");
		for (ProtocolResolver protocolResolver : this.protocolResolvers) {    // 1
			Resource resource = protocolResolver.resolve(location, this);
			if (resource != null) {return resource;}
		}
 
		if (location.startsWith("/")) {return getResourceByPath(location);}    //2
		else if (location.startsWith(CLASSPATH_URL_PREFIX)) {           //3
			return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
		}
		else {
			try {
				// Try to parse the location as a URL...
				URL url = new URL(location);               //4
				return new UrlResource(url);
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
				return getResourceByPath(location);           //5
			}
		}
	}

步骤1,先用扩展协议解析器解析资源地址并返回。举个例子,咱们可以自定义资源解析器来完成带前缀“classpath:”的解析:

首先实现ProtocolResolver接口:

class ClasspathPreProtocolResolver implements ProtocolResolver{
           private static String CLASS_PATH_PRE="classpath:";        
        public Resource resolve(String location, ResourceLoader resourceLoader) {
           if( location.startsWith(CLASS_PATH_PRE)) {
                return new ClassPathResource(location.substring(CLASS_PATH_PRE.length()));
           }       
           return null;
        }        
    }

步骤2,假设location以斜杠开头,则调用该类中 getResourceByPath(String path)方法 ,代码如下:

protected Resource getResourceByPath(String path) {
		return new ClassPathContextResource(path, getClassLoader());
	}

步骤三,假如资源表达式以classpath开头,则截取除前缀calsspath:的路径,并做为ClassPathResource的构造参数,生成ClassPathResource实例后返回。咱们可以在web.xml中做如下配置:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/config/applicationContext.xml</param-value>
</context-param>

6、通过refresh()内部的实现我们大致可以了解整个refresh()方法担负了整个Spring容器初始化和加载的所有逻辑,包括Bean工厂的初始化、post-processor的注册以及调用、bean的实例化、事件发布等。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java连接mysql数据库详细步骤解析

    java连接mysql数据库详细步骤解析

    以下是对java连接mysql数据库的具体详细步骤进行了分析介绍,需要的朋友可以过来参考下
    2013-08-08
  • Spring零基础到进阶之使用方法详解

    Spring零基础到进阶之使用方法详解

    Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能
    2022-07-07
  • Java如何通过反射取实体类字段取值

    Java如何通过反射取实体类字段取值

    这篇文章主要介绍了Java如何通过反射取实体类字段取值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-07-07
  • flutter TabBarView 动态添加删除页面的示例代码

    flutter TabBarView 动态添加删除页面的示例代码

    在Flutter中使用TabBarView动态添加和删除页面时,如果未为每个页面设置唯一的key,会导致删除页面时出现状态错误或删除错误的页面,正确的做法是为每个页面指定全局唯一的key,这样可以确保页面在添加和删除时状态正确,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • spring源码下载、编译、debug的详细教程

    spring源码下载、编译、debug的详细教程

    这篇文章主要介绍了spring源码下载、编译、debug的详细教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • Java中excel表数据的批量导入方法

    Java中excel表数据的批量导入方法

    这篇文章主要为大家详细介绍了Java中excel表数据的批量导入方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-05-05
  • Java之MyBatis入门详解

    Java之MyBatis入门详解

    这篇文章主要介绍了Java之MyBatis入门详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • 详解Java注解实现自己的ORM

    详解Java注解实现自己的ORM

    这篇文章主要介绍了Java注解实现自己的ORM知识,本文通过示例代码给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2022-10-10
  • Mybatis基于注解形式的sql语句生成实例代码

    Mybatis基于注解形式的sql语句生成实例代码

    这篇文章主要介绍了 Mybatis基于注解形式的sql语句生成实例代码,需要的朋友可以参考下
    2017-09-09
  • SVN导入maven项目报错解决方案

    SVN导入maven项目报错解决方案

    这篇文章主要介绍了SVN导入maven项目报错解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-12-12

最新评论