0

I see the following code snippet in the WebApplicationInitializer.onStartup():

    // 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);

So basically, the ctx is shared between the DispatcherServlet and the InitServlet (this is just a custom HttpServlet).

I am new to Spring and not quite sure about the proper use of various application contexts.

For now, I think each servlet should have its own application context. If there're beans to be shared, they should be put in the Root application context.

So it seems the author wants to put everything into a single big DispatcherServlet application context. Is it OK? Any caveat?

ADD1

A related link: Multiple application context, multiple dispatcher servlets?

Community
  • 1
  • 1
smwikipedia
  • 61,609
  • 92
  • 309
  • 482
  • 1
    If your concern is `ServletContext`, then here's food for read: http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading/ – BalusC Nov 02 '15 at 14:06
  • @BalusC Thanks. `ServletContext` is not a Spring concept. What I am concerned is the `Spring Application Context`, which is used to hold beans. But that link is very informative. – smwikipedia Nov 02 '15 at 14:10

1 Answers1

0

DispatcherServlet is essentially a servlet. And a Spring application context usually holds a bunch of singleton objects. So this question basically boils down to: Is it OK for 2 servlets to query their dependent objects from a mutual repository?

If the 2 servlets serve drastically different purposes, it may be rational to put their dependent objects into respective application contexts. But so far I see no strong reason to do that but a matter of opinion.

smwikipedia
  • 61,609
  • 92
  • 309
  • 482