Servlet容器初始化IOC容器

红太狼 2022-01-28 11:53 459阅读 0赞

Servlet容器初始化IOC容器

  1. <!-- ServletContext参数,配置Ioc容器的xml文件名 -->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>classpath:applicationContext.xml</param-value>
  5. </context-param>
  6. <!-- 初始化Ioc容器的监听器(重点就是这个监听器)-->
  7. <listener>
  8. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  9. </listener>

看下这个监听器:

  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
  2. public ContextLoaderListener() {
  3. }
  4. public ContextLoaderListener(WebApplicationContext context) {
  5. super(context);
  6. }
  7. @Override
  8. public void contextInitialized(ServletContextEvent event) {
  9. initWebApplicationContext(event.getServletContext());
  10. }
  11. public void contextDestroyed(ServletContextEvent event) {
  12. closeWebApplicationContext(event.getServletContext());
  13. ContextCleanupListener.cleanupAttributes(event.getServletContext());
  14. }
  15. }

这个监听器首先实现了ServletContextListener,所以会在Servlet容器初始化和销毁的时候分别调用contextInitialized( )与contextDestroyed( )方法。

注意这里的带参构造方法 ContextLoaderListener(WebApplicationContext context)是调用了父类ContextLoader的构造方法,并传参进去。

而ContextLoader的主要作用就是初始化Ioc容器,下面我们来看看ContextLoader这个类

  1. public class ContextLoader {
  2. public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";//ServletContext上下文参数
  3. private WebApplicationContext context;
  4. public ContextLoader(WebApplicationContext context) {
  5. this.context = context;
  6. }
  7. public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  8. if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  9. throw new IllegalStateException(
  10. "Cannot initialize context because there is already a root application context present - " +
  11. "check whether you have multiple ContextLoader* definitions in your web.xml!");
  12. }//不能初始化Ioc容器,因为已经有一个根Application上下文,检查在web.xml中是否有多个ContextLoader
  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. }//开始初始化WebApplicationContext
  18. long startTime = System.currentTimeMillis();//当前毫秒数
  19. try {
  20. // Store context in local instance variable, to guarantee that
  21. // it is available on ServletContext shutdown.
  22. if (this.context == null) {
  23. this.context = createWebApplicationContext(servletContext);
  24. }
  25. if (this.context instanceof ConfigurableWebApplicationContext) {
  26. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
  27. if (!cwac.isActive()) {//Ioc容器并未初始化,所以暂时不能提供服务
  28. // The context has not yet been refreshed -> provide services such as
  29. // setting the parent context, setting the application context id, etc
  30. if (cwac.getParent() == null) {//设置父applicationContext
  31. // The context instance was injected without an explicit parent ->
  32. // determine parent for root web application context, if any.
  33. ApplicationContext parent = loadParentContext(servletContext);
  34. cwac.setParent(parent);
  35. }
  36. configureAndRefreshWebApplicationContext(cwac, servletContext);
  37. }
  38. }
  39. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  40. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  41. if (ccl == ContextLoader.class.getClassLoader()) {
  42. currentContext = this.context;
  43. }
  44. else if (ccl != null) {
  45. currentContextPerThread.put(ccl, this.context);
  46. }
  47. if (logger.isDebugEnabled()) {
  48. logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
  49. WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
  50. }
  51. if (logger.isInfoEnabled()) {
  52. long elapsedTime = System.currentTimeMillis() - startTime;
  53. logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
  54. }
  55. return this.context;
  56. }
  57. catch (RuntimeException ex) {
  58. logger.error("Context initialization failed", ex);
  59. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  60. throw ex;
  61. }
  62. catch (Error err) {
  63. logger.error("Context initialization failed", err);
  64. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  65. throw err;
  66. }
  67. }

这里是总过程的描述:

  1. protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
  2. Class<?> contextClass = determineContextClass(sc);//获取context是由那个类定义的
  3. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {//判断是否为同一个类,或是子类
  4. throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
  5. "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
  6. }
  7. return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
  8. }

通过determineContextClass( )知道了实例化IOC容器方式,然后用这个方式,再通过反射机制实例化容器,即实例化webApplicationContext。

  1. protected Class<?> determineContextClass(ServletContext servletContext) {
  2. String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);//该属性为"ContextClass"
  3. if (contextClassName != null) {
  4. try {
  5. return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
  6. }
  7. catch (ClassNotFoundException ex) {
  8. throw new ApplicationContextException(
  9. "Failed to load custom context class [" + contextClassName + "]", ex);
  10. }
  11. }
  12. else {
  13. contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
  14. try {
  15. return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
  16. }
  17. catch (ClassNotFoundException ex) {
  18. throw new ApplicationContextException(
  19. "Failed to load default context class [" + contextClassName + "]", ex);
  20. }
  21. }
  22. }

因为实例化Ioc容器的方式有几种,而这个方法是判定需要实例化那种类来实例化当前Web容器的Spring Ioc根容器。要判定需要实例化哪种类来实例化当前web容器的Spring根容器,如果我们设置了名称为“contextClass”的context-param,则取我们设置的类,该类应当实现ConfigurableWebApplicationContext接口或继承自实现了该接口的子类(如XmlWebApplicationContext、GroovyWebApplicationContext和AnnotationConfigWebApplicationContext),通常我们都不会设置,Spring会默认取与ContextLoader同目录下的ContextLoader.properties中记录的类名作为根容器的类型(默认是org.springframework.web.context.support.XmlWebApplicationContext);

  1. protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
  2. if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
  3. // The application context id is still set to its original default value
  4. // -> assign a more useful id based on available information
  5. String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
  6. if (idParam != null) {
  7. wac.setId(idParam);
  8. }
  9. else {
  10. // Generate default id...
  11. wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
  12. ObjectUtils.getDisplayString(sc.getContextPath()));
  13. }
  14. }
  15. wac.setServletContext(sc);
  16. String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
  17. if (configLocationParam != null) {
  18. wac.setConfigLocation(configLocationParam);
  19. }
  20. // The wac environment's #initPropertySources will be called in any case when the context
  21. // is refreshed; do it eagerly here to ensure servlet property sources are in place for
  22. // use in any post-processing or initialization that occurs below prior to #refresh
  23. ConfigurableEnvironment env = wac.getEnvironment();
  24. if (env instanceof ConfigurableWebEnvironment) {
  25. ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
  26. }
  27. customizeContext(sc, wac);
  28. wac.refresh();
  29. }

虽然实例化了IOC容器,但是并未完成IOC容器的初始化,还不能提供服务。该方法的逻辑主要有一下几点:设置一个contextId(从contextId这个param获取,如果没有则默认是WebApplicationContext的类名 + “:” + servlet context的路径);设置配置位置(从contextConfigLocation 这个param获取,如果未配置,则默认是/WEB-INF/applicationContext.xml,在XmlWebApplicationContext中可以看出);自定义该congtext;调用该Context的refresh()方法。

上面描述了WebApplicationContext的构造,默认还是使用反射的方式构建XmlWebApplicationContext实例

  1. public void closeWebApplicationContext(ServletContext servletContext) {
  2. servletContext.log("Closing Spring root WebApplicationContext");
  3. try {
  4. if (this.context instanceof ConfigurableWebApplicationContext) {
  5. ((ConfigurableWebApplicationContext) this.context).close();
  6. }
  7. }
  8. finally {
  9. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  10. if (ccl == ContextLoader.class.getClassLoader()) {
  11. currentContext = null;
  12. }
  13. else if (ccl != null) {
  14. currentContextPerThread.remove(ccl);
  15. }
  16. servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  17. if (this.parentContextRef != null) {
  18. this.parentContextRef.release();
  19. }
  20. }
  21. }

该方法完成了对Ioc容器的销毁。

PS:webApplicationContext实现了ApplicationContext接口的子类。是专门为WEB应用准备的。

  1. 它允许从相对于Web根目录的路径中加载配置文件完成初始化工作。从WebApplicationContext中可以获取ServletContext引用,整个Web应用上下文对象将作为属性放置在ServletContext中,以便Web应用环境可以访问Spring上下文。
    2.WebApplicationContext还为Bean提供了三个新的作用域,request、session和globalsession。
    其中两个参数HttpServletRequest:服务器从客户端拿去数据
    HttpServletResponse:服务器向前台传送数据

原文:https://blog.csdn.net/Wayne\_y/article/details/79778207

发表评论

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

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

相关阅读