Spring: How should application+web contexts be organized?

后端 未结 1 1697
予麋鹿
予麋鹿 2021-01-21 01:06

The scenario:

  1. Start the app and load ClassPathXmlApplicationContext in main(), this starts a Jetty webapp.
  2. dispatcher servlet then loads a
1条回答
  •  -上瘾入骨i
    2021-01-21 01:28

    Context #1 is not connected to other contexts at all, it is just an implementation detail of how you start up your webserver (Jetty). Contexts #2 and #3 are somewhat explained in Spring reference documentation.

    • Context #2 is loaded from WEB-INF/[servlet-name]-servlet.xml. As there can be many DispatcherServlets, there may be more than one such a context in single webapp, for different servlets.
    • Context #3 is typically loaded from WEB-INF/applicationContext.xml and you have to take special steps to have it loaded (use ContextLoaderListener). This loaded context becomes the parent context (shared) of all specific servlet contexts in particular web application. As such, it is suitable for loading business service beans and database access beans.

    The setup you outlined is perfectly OK. In fact, I would call it the recommended setup, as it keeps things simple and close to the way Spring contexts are constructed in a typical webapp.

    However:

    You may get rid of context #3 if you do not want to keep your business beans in separate context. However, I would recommend you to keep them separate (you might need to move them to a different machine later on and make available over some sort of remoting mechanism).

    Another reason to get rid of context #3: you might want to share your business beans among several webapps. The in order to achieve this you would need a special subclass of Spring ContextLoader and then do some magic while Jetty is starting up your webapps. I have done this and can provide some advice, if needed.

    Finally, you may get rid of context #1 and replace that with old-school pure java code that would bootstrap Jetty. This decision is 100% up to you and matter of preference. For the record, I also like to use a separate Spring applicationContext for bootstrapping Jetty.

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