所在类:org.springframework.web.servlet.FrameworkServlet

    1. protected WebApplicationContext initWebApplicationContext() {
    2. WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    3. WebApplicationContext wac = null;
    4. if (this.webApplicationContext != null) {
    5. // A context instance was injected at construction time -> use it wac = this.webApplicationContext;
    6. if (wac instanceof ConfigurableWebApplicationContext) {
    7. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
    8. if (!cwac.isActive()) {
    9. // The context has not yet been refreshed -> provide services such as
    10. // setting the parent context, setting the application context id, etc
    11. if (cwac.getParent() == null) {
    12. // The context instance was injected without an explicit parent -> set
    13. // the root application context (if any; may be null) as the parent
    14. cwac.setParent(rootContext);
    15. }
    16. configureAndRefreshWebApplicationContext(cwac);
    17. }
    18. }
    19. }
    20. if (wac == null) {
    21. // No context instance was injected at construction time -> see if one
    22. // has been registered in the servlet context. If one exists, it is assumed
    23. // that the parent context (if any) has already been set and that the
    24. // user has performed any initialization such as setting the context id
    25. wac = findWebApplicationContext();
    26. }
    27. if (wac == null) {
    28. // No context instance is defined for this servlet -> create a local one
    29. // 创建WebApplicationContext
    30. wac = createWebApplicationContext(rootContext);
    31. }
    32. if (!this.refreshEventReceived) {
    33. // Either the context is not a ConfigurableApplicationContext with refresh
    34. // support or the context injected at construction time had already been
    35. // refreshed -> trigger initial onRefresh manually here.
    36. synchronized (this.onRefreshMonitor) {
    37. // 刷新WebApplicationContext onRefresh(wac);
    38. }
    39. }
    40. if (this.publishContext) {
    41. // Publish the context as a servlet context attribute.
    42. // 将IOC容器在应用域共享
    43. String attrName = getServletContextAttributeName();
    44. getServletContext().setAttribute(attrName, wac);
    45. }
    46. return wac;
    47. }