Spring MVC Web应用程序中的根上下文和分派器servlet上下文到底如何?
问题内容:
我正在学习 Spring MVC ,所以我有一些疑问
因此,我有一个配置类,用于配置处理用户请求的 DispatcherServlet :
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = ...
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("main", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("main/");
}
}
我很清楚 DispatcherServlet的 工作方式。我的怀疑与 上下文 概念有关。
1)确切地表示 上下文 ?我认为这就像一组具有特定用途的豆类,可以在环境中工作。但是我绝对不是这个主张。
2) 根上下文 和 调度程序servlet上下文有 什么区别?
3)据我了解,在 dispatcherContext中 定义的bean 可以访问在 rootContext中 定义的 bean
(但事实并非如此)。为什么?
特纳克斯
问题答案:
根上下文
Spring应用程序中的根上下文ApplicationContext
是由加载的ContextLoaderListener
。此上下文应具有全球可用的资源,例如服务,存储库,基础结构Bean(DataSource
,EntityManagerFactory
s等)等。
该ContextLoaderListener
注册此背景下的ServletContext
名下org.springframework.web.context.WebApplicationContext.ROOT
。
如果您ApplicationContext
自己加载并在上方使用上面的名称注册ServletContext
,则将其视为根上下文。
子语境
Spring应用程序中的子上下文ApplicationContext
是由DispatcherServlet
(或例如MessageDispatcherServlet
Spring-
WS应用程序中的)加载的。对于Spring
MVC,此上下文应仅包含与该上下文相关的bean,例如ViewResolver
s,HandlerMapping
s等。
Servlet
ServletContext
在名称下以形式注册此上下文org.springframework.web.servlet.FrameworkServlet.CONTEXT.<servlet- name>
。
根<儿童关系
只有子上下文可以访问父上下文,因为您可以拥有多个子上下文。例如,在结合了Spring WS应用程序的Spring
MVC中。子级通过在父级上下文中找到ServletContext
众所周知的名称来检测父级上下文。
如果根上下文可以访问该子项,那么它将使用哪个来关联bean?如果是这种情况,那么接下来,当涉及AOP时,您还将得到令人惊讶的结果。在子上下文中定义的AOP会突然影响在根上下文中配置的Bean。