【问题标题】:Is it OK for a HttpServlet to share application context with the Spring DispatcherServlet?HttpServlet 可以与 Spring DispatcherServlet 共享应用程序上下文吗?
【发布时间】:2016-02-02 10:34:31
【问题描述】:

我在WebApplicationInitializer.onStartup()中看到如下代码sn-p:

    // The app context is created here.
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(AppWebConfig.class);
    ctx.setServletContext(servletContext);

    // The app context is given to the DispatcherServlet: the new DispatcherServlet(ctx)
    Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    dynamic.setAsyncSupported(true);
    dynamic.addMapping("/");
    dynamic.setLoadOnStartup(1);
    dynamic.addMapping("*.*");

    // And the app context is given to InitServlet as well: the new InitServlet(ctx)
    Dynamic initServlet = servletContext.addServlet("initServlet", new InitServlet(ctx));
    initServlet.setLoadOnStartup(2);

所以基本上,ctxDispatcherServletInitServlet 之间共享(这只是一个自定义的 HttpServlet)。

我是 Spring 新手,不太确定如何正确使用各种应用程序上下文。

目前,我认为每个 servlet 都应该有自己的应用程序上下文。如果有beans to be shared,则应放在Root application context 中。

所以作者似乎想将所有内容放入a single big DispatcherServlet 应用程序上下文中。可以吗?有什么注意事项吗?

添加1

相关链接: Multiple application context, multiple dispatcher servlets?

【问题讨论】:

  • 如果你关心的是ServletContext,那么这里是阅读的食物:stackoverflow.com/questions/3106452/…
  • @BalusC 谢谢。 ServletContext 不是 Spring 概念。我关心的是Spring Application Context,它是用来装豆子的。但该链接信息量很大。

标签: spring spring-mvc servlets applicationcontext


【解决方案1】:

DispatcherServlet 本质上是一个 servlet。 Spring 应用程序上下文通常包含一堆singleton 对象。所以这个问题基本上可以归结为:是否可以让 2 个 servlet 从相互存储库中查询它们的依赖对象

如果这 2 个 servlet 的用途截然不同,那么将它们的依赖对象放入各自的应用程序上下文中可能是合理的。但到目前为止,我认为没有充分的理由这样做,只是见仁见智

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2019-05-12
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多