spring与springmvc父子容器

小灰灰 2020-05-08 05:53 1044阅读 0赞

1、spring和springmvc父子容器概念介绍

在spring和springmvc进行整合的时候,一般情况下我们会使用不同的配置文件来配置spring和springmvc,因此我们的应用中会存在至少2个ApplicationContext实例,由于是在web应用中,因此最终实例化的是ApplicationContext的子接口WebApplicationContext。如下图所示:

上图中显示了2个WebApplicationContext实例,为了进行区分,分别称之为:Servlet WebApplicationContext、Root WebApplicationContext。 其中:

Servlet WebApplicationContext:这是对J2EE三层架构中的web层进行配置,如控制器(controller)、视图解析器(view resolvers)等相关的bean。通过spring mvc中提供的DispatchServlet来加载配置,通常情况下,配置文件的名称为spring-servlet.xml。

Root WebApplicationContext:这是对J2EE三层架构中的service层、dao层进行配置,如业务bean,数据源(DataSource)等。通常情况下,配置文件的名称为applicationContext.xml。在web应用中,其一般通过ContextLoaderListener来加载。

以下是一个web.xml配置案例:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  5. <!—创建Root WebApplicationContext-->
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
  9. </context-param>
  10. <listener>
  11. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  12. </listener>
  13. <!—创建Servlet WebApplicationContext-->
  14. <servlet>
  15. <servlet-name>dispatcher</servlet-name>
  16. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  17. <init-param>
  18. <param-name>contextConfigLocation</param-name>
  19. <param-value>/WEB-INF/spring/spring-servlet.xml</param-value>
  20. </init-param>
  21. <load-on-startup>1</load-on-startup>
  22. </servlet>
  23. <servlet-mapping>
  24. <servlet-name>dispatcher</servlet-name>
  25. <url-pattern>/*</url-pattern>
  26. </servlet-mapping>
  27. </web-app>

在上面的配置中:

1、 ContextLoaderListener会被优先初始化时,其会根据元素中contextConfigLocation参数指定的配置文件路径,在这里就是”/WEB-INF/spring/applicationContext.xml”,来创建WebApplicationContext实例。 并调用ServletContext的setAttribute方法,将其设置到ServletContext中,属性的key为”org.springframework.web.context.WebApplicationContext.ROOT”,最后的”ROOT”字样表明这是一个 Root WebApplicationContext。

2、DispatcherServlet在初始化时,会根据元素中contextConfigLocation参数指定的配置文件路径,即”/WEB-INF/spring/spring-servlet.xml”,来创建Servlet WebApplicationContext。同时,其会调用ServletContext的getAttribute方法来判断是否存在Root WebApplicationContext。如果存在,则将其设置为自己的parent。这就是父子上下文(父子容器)的概念。

​ 父子容器的作用在于,当我们尝试从child context(即:Servlet WebApplicationContext)中获取一个bean时,如果找不到,则会委派给parent context (即Root WebApplicationContext)来查找。

​ 如果我们没有通过ContextLoaderListener来创建Root WebApplicationContext,那么Servlet WebApplicationContext的parent就是null,也就是没有parent context。

2、为什么要有父子容器

笔者理解,父子容器的作用主要是划分框架边界。

在J2EE三层架构中,在service层我们一般使用spring框架, 而在web层则有多种选择,如spring mvc、struts等。因此,通常对于web层我们会使用单独的配置文件。例如在上面的案例中,一开始我们使用spring-servlet.xml来配置web层,使用applicationContext.xml来配置service、dao层。如果现在我们想把web层从spring mvc替换成struts,那么只需要将spring-servlet.xml替换成Struts的配置文件struts.xml即可,而applicationContext.xml不需要改变。

事实上,如果你的项目确定了只使用spring和spring mvc的话,你甚至可以将service 、dao、web层的bean都放到spring-servlet.xml中进行配置,并不是一定要将service、dao层的配置单独放到applicationContext.xml中,然后使用ContextLoaderListener来加载。在这种情况下,就没有了Root WebApplicationContext,只有Servlet WebApplicationContext。

3、**Root WebApplicationContext创建过程**源码分析

​ ContextLoaderListener用于创建ROOT WebApplicationContext,其实现了ServletContextListener接口的contextInitialized和contextDestroyed方法,在web应用启动和停止时,web容器(如tomcat)会负责回调这两个方法。而创建Root WebApplicationContext就是在contextInitialized中完成的,相关源码片段如下所示:

org.springframework.web.context.ContextLoaderListener

  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
  2. //...
  3. @Override
  4. public void contextInitialized(ServletContextEvent event) {
  5. initWebApplicationContext(event.getServletContext());
  6. }
  7. //...
  8. }

可以看到ContextLoaderListener继承了ContextLoader类,真正的创建在操作,是在ContextLoader的initWebApplicationContext方法中完成。

org.springframework.web.context.ContextLoader#initWebApplicationContext

  1. public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  2. //1、保证只能有一个ROOT WebApplicationContext
  3. //尝试以”org.springframework.web.context.WebApplicationContext.ROOT”为key从ServletContext中查找WebApplicationContext实例
  4. //如果已经存在,则抛出异常。
  5. //一个典型的异常场景是在web.xml中配置了多个ContextLoaderListener,那么后初始化的ContextLoaderListener就会抛出异常
  6. if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  7. throw new IllegalStateException(
  8. "Cannot initialize context because there is already a root application context present - " +
  9. "check whether you have multiple ContextLoader* definitions in your web.xml!");
  10. }
  11. //2、打印日志,注意日志中的提示内容:"Initializing Spring root WebApplicationContext”
  12. //这验证了我们之前的说法,ContextLoaderListener创建的是root WebApplicationContext
  13. Log logger = LogFactory.getLog(ContextLoader.class);
  14. servletContext.log("Initializing Spring root WebApplicationContext");
  15. if (logger.isInfoEnabled()) {
  16. logger.info("Root WebApplicationContext: initialization started");
  17. }
  18. long startTime = System.currentTimeMillis();
  19. try {
  20. if (this.context == null) {
  21. // 3 创建WebApplicationContext实现类实例。其内部首先会确定WebApplicationContext实例类型。
  22. // 首先判断有没有<context-param>元素的<param-name>值为contextClass,如果有,则对应的<param-value>值,就是要创建的WebApplicationContext实例类型
  23. // 如果没有指定,则默认的实现类为XmlWebApplicationContext。这是在spring-web-xxx.jar包中的ContextLoader.properties指定的
  24. // 注意这个时候,只是创建了WebApplicationContext对象实例,还没有加载对应的spring配置文件
  25. this.context = createWebApplicationContext(servletContext);
  26. }
  27. //4 XmlWebApplicationContext实现了ConfigurableWebApplicationContext接口,因此会进入if代码块
  28. if (this.context instanceof ConfigurableWebApplicationContext) {
  29. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
  30. // 4.1 由于WebApplicationContext对象实例还没有加载对应配置文件,spring上下文还没有被刷新,因此isActive返回false,进入if代码块
  31. if (!cwac.isActive()) {
  32. //4.2 当前ROOT WebApplicationContext的父context为null,则尝试通过loadParentContext方法获取父ApplicationContext,并设置到其中
  33. //由于loadParentContext方法目前写死返回null,因此可以忽略4.2这个步骤。
  34. if (cwac.getParent() == null) {
  35. ApplicationContext parent = loadParentContext(servletContext);
  36. cwac.setParent(parent);
  37. }
  38. //4.3 加载配置spring文件。根据<context-param>指定的contextConfigLocation,确定配置文件的位置。
  39. configureAndRefreshWebApplicationContext(cwac, servletContext);
  40. }
  41. }
  42. // 5、将创建的WebApplicationContext实例以”org.springframework.web.context.WebApplicationContext.ROOT”为key设置到ServletContext中
  43. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  44. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  45. if (ccl == ContextLoader.class.getClassLoader()) {
  46. currentContext = this.context;
  47. }
  48. else if (ccl != null) {
  49. currentContextPerThread.put(ccl, this.context);
  50. }
  51. if (logger.isDebugEnabled()) {
  52. logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
  53. WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
  54. }
  55. if (logger.isInfoEnabled()) {
  56. long elapsedTime = System.currentTimeMillis() - startTime;
  57. logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
  58. }
  59. return this.context;
  60. }
  61. catch (RuntimeException ex) {
  62. logger.error("Context initialization failed", ex);
  63. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  64. throw ex;
  65. }
  66. catch (Error err) {
  67. logger.error("Context initialization failed", err);
  68. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  69. throw err;
  70. }
  71. }

4、Servlet WebApplicationContext创建过程源码分析

​ DispatcherServlet负责创建Servlet WebApplicationContext,并尝试将ContextLoaderListener创建的ROOT WebApplicationContext设置为自己的parent。其类图继承关系如下所示:

其中HttpServletBean继承了HttpServlet,因此在应用初始化时,其init方法会被调用,如下:

org.springframework.web.servlet.HttpServletBean#init

  1. public final void init() throws ServletException {
  2. //...
  3. // 这个方法在HttpServletBean中是空实现
  4. initServletBean();
  5. if (logger.isDebugEnabled()) {
  6. logger.debug("Servlet '" + getServletName() + "' configured successfully");
  7. }
  8. }

HttpServletBean的init方法中,调用了initServletBean()方法,在HttpServletBean中,这个方法是空实现。FrameworkServlet覆盖了HttpServletBean中的initServletBean方法,如下:

org.springframework.web.servlet.FrameworkServlet#initServletBean

  1. @Override
  2. protected final void initServletBean() throws ServletException {
  3. getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
  4. if (this.logger.isInfoEnabled()) {
  5. this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
  6. }
  7. long startTime = System.currentTimeMillis();
  8. try {
  9. // initWebApplicationContext方法中,创建了Servlet WebApplicationContext实例
  10. this.webApplicationContext = initWebApplicationContext();
  11. initFrameworkServlet();
  12. }
  13. catch (ServletException ex) {
  14. this.logger.error("Context initialization failed", ex);
  15. throw ex;
  16. }
  17. catch (RuntimeException ex) {
  18. this.logger.error("Context initialization failed", ex);
  19. throw ex;
  20. }
  21. if (this.logger.isInfoEnabled()) {
  22. long elapsedTime = System.currentTimeMillis() - startTime;
  23. this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
  24. elapsedTime + " ms");
  25. }
  26. }

上述代码片段中,我们可以看到通过调用FrameworkServlet的另一个方法initWebApplicationContext(),来真正创建WebApplicationContext实例,其源码如下:

org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext

  1. protected WebApplicationContext initWebApplicationContext() {
  2. //1 通过工具类WebApplicationContextUtils来获取Root WebApplicationContext
  3. // 其内部以”org.springframework.web.context.WebApplicationContext.ROOT”为key从ServletContext中查找WebApplicationContext实例作为rootContext
  4. WebApplicationContext rootContext =
  5. WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  6. WebApplicationContext wac = null;
  7. //2、在我们的案例中是通过web.xml配置的DispatcherServlet,此时webApplicationContext为null,因此不会进入以下代码块
  8. if (this.webApplicationContext != null) {
  9. // A context instance was injected at construction time -> use it
  10. wac = this.webApplicationContext;
  11. if (wac instanceof ConfigurableWebApplicationContext) {
  12. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
  13. if (!cwac.isActive()) {
  14. // The context has not yet been refreshed -> provide services such as
  15. // setting the parent context, setting the application context id, etc
  16. if (cwac.getParent() == null) {
  17. // The context instance was injected without an explicit parent -> set
  18. // the root application context (if any; may be null) as the parent
  19. cwac.setParent(rootContext);
  20. }
  21. configureAndRefreshWebApplicationContext(cwac);
  22. }
  23. }
  24. }
  25. //3 经过第二步,wac依然为null,此时尝试根据FrameServlet的contextAttribute 字段的值,从ServletContext中获取Servlet WebApplicationContext实例,在我们的案例中,contextAttribute值为空,因此这一步过后,wac依然为null
  26. if (wac == null) {
  27. // No context instance was injected at construction time -> see if one
  28. // has been registered in the servlet context. If one exists, it is assumed
  29. // that the parent context (if any) has already been set and that the
  30. // user has performed any initialization such as setting the context id
  31. wac = findWebApplicationContext();
  32. }
  33. //4 开始真正的创建Servlet WebApplicationContext,并将rootContext设置为parent
  34. if (wac == null) {
  35. // No context instance is defined for this servlet -> create a local one
  36. wac = createWebApplicationContext(rootContext);
  37. }
  38. if (!this.refreshEventReceived) {
  39. // Either the context is not a ConfigurableApplicationContext with refresh
  40. // support or the context injected at construction time had already been
  41. // refreshed -> trigger initial onRefresh manually here.
  42. onRefresh(wac);
  43. }
  44. if (this.publishContext) {
  45. // Publish the context as a servlet context attribute.
  46. String attrName = getServletContextAttributeName();
  47. getServletContext().setAttribute(attrName, wac);
  48. if (this.logger.isDebugEnabled()) {
  49. this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
  50. "' as ServletContext attribute with name [" + attrName + "]");
  51. }
  52. }
  53. return wac;
  54. }

5 java方式配置

最后,对于Root WebApplicationContext和Servlet WebApplicationContext的创建,我们也可以通过java代码的方式进行配置。spring通过以下几个类对此提供了支持:

AbstractContextLoaderInitializer:其用于动态的往ServletContext中注册一个ContextLoaderListener,从而创建Root WebApplicationContext

AbstractDispatcherServletInitializer:其用于动态的往ServletContext中注册一个DispatcherServlet,从而创建Servlet WebApplicationContext

对应的类图继承关系如下所示:

AbstractAnnotationConfigDispatcherServletInitializer用于提供AbstractContextLoaderInitializer和AbstractDispatcherServletInitializer所需要的配置。

AbstractAnnotationConfigDispatcherServletInitializer中有3个抽象方法需要实现:

  1. public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  2. //获得创建Root WebApplicationContext所需的配置类
  3. @Override
  4. protected Class<?>[] getRootConfigClasses() {
  5. return new Class<?[] { RootConfig.class };
  6. }
  7. //获得创建Servlet WebApplicationContext所需的配置类
  8. @Override
  9. protected Class<?>[] getServletConfigClasses() {
  10. return new Class<?[] { App1Config.class };
  11. }
  12. //获得DispatchServlet拦截的url
  13. @Override
  14. protected String[] getServletMappings() {
  15. return new String[] { "/app1/*" };
  16. }
  17. }

发表评论

表情:
评论列表 (有 0 条评论,1044人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring父子容器

    一、痛点 当前开发工程以来的spring-boot-starter脚手架,配置了很多通用的bean,而部分无法满足自身需求,因此需要自定义bean,这时候就有可能