Spring --- 你真的明白Spring上下文之间的关系吗?

/ Java / 没有评论 / 1846浏览

使用Spring MVC的时候会遇到3个上下文,从上到下分别是ServletContext, WebApplicationContext以及DispatcherServlet所在的MVC Context(本文用的名字,方便交流),本文帮助完全弄明白他们之间的关系

上下文之间关系

本节内容完全COPY halty的回复,只是修改了一些拼写错误,鼓励大家去看原文

要想很好理解这三个上下文的关系,需要先熟悉spring是怎样在web容器中启动起来的。spring的启动过程其实就是其IoC容器的启动过程,对于web程序,IoC容器启动过程即是建立上下文的过程。

引申的提问或结论

WebApplicationContext 是MVC Context的父上下文,是否可以互相注入对方的bean? WebApplicationContext中的bean可以注入到MVC Context的bean中,反向不可以(亲测)。参见一下代码:来自AbstractBeanFactory

// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    // Not found -> check parent.
    String nameToLookup = originalBeanName(name);
    if (args != null) {
        // Delegation to parent with explicit args.
        return (T) parentBeanFactory.getBean(nameToLookup, args);
    }
    else {
        // No args -> delegate to standard getBean method.
        return parentBeanFactory.getBean(nameToLookup, requiredType);
    }
}

如果同一个bean被两个上下文扫描到,会怎么样?是不是有两个实例? 是的,会在两个上下文中生成两个独立的bean(亲测)

web.xml为什么有时候需要ContextLoaderListener,有时候又不需要? 其实是需要的,有时候不需要是因为不小心把其他的bean全部扫描进DispatchServlet的MVC Context里面了,所以不需要再加载WebApplicationContext(亲测)

是不是可以只配置MVC Context而不使用WebApplicationContext? 亲测可以(但是很少这么使用,原因我还不清楚,如果你知道,还请指教,不胜感激)

参考