Why does Spring MVC need at least two contexts?

前端 未结 3 806
遥遥无期
遥遥无期 2020-11-29 20:40

In Spring MVC, there are two contexts. One is the application context or global context which is booted up by ContextLoaderListener. It takes all the configurat

相关标签:
3条回答
  • 2020-11-29 21:02

    Having a root web application context plus a child servlet context is just an option. If you know that your application won't have a second servlet, it's arguably simpler to have one single Spring context for the whole web application.

    You can achieve that setup by simply removing the ContextLoaderListener (and the accompanying contextConfigLocation context-param) from your web.xml and moving all bean definitions into the xml defining the servlet context ([servlet-name]-servlet.xml).

    This is possible, because the FrameworkServlet (super-class of DispatcherServlet) doesn't care if there is a root application context when creating the servlet context. It just relays the root context as the parent if available. See related code here.

    0 讨论(0)
  • 2020-11-29 21:18

    Imagine you had two separate Dispatchers, each serving a different purpose, and each having its own dependencies. You would configure those independently using separate contexts.

    If there is any shared configuration, this can go in the 'global' context.

    I don't think it's possible to have only one context using DispatcherServlet, as it creates its own context and links it to the parent context (via the FrameworkServlet superclass).

    FrameworkServlet.createWebApplicationContext

    0 讨论(0)
  • 2020-11-29 21:25

    Check this answer About multiple containers in spring framework

    Yes ,you can have one context only.

    For code reuse it would be better to isolate services in Application Context rather then WebApplicationContext.but this not compulsion.you can keep only webApplicationcontext only.

    0 讨论(0)
提交回复
热议问题