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?