DEV Community

PGD
PGD

Posted on

ApplicationContext, DispatcherServlet, ContextLoaderListener

A context indicates an instance of Spring bean container. If we want a DispatcherServlet to dispatch the request to beans annotated with @Controller (i.e., controllers), we should provide a context containing controller beans, in other words, we should pass the location of metadata of Spring context to DispatcherServlet so that it can generate his Spring context. Typically, Spring context DispatcherServlet has contains beans related to Web MVC, such as controllers or rest controllers (beans annotated with @Controller or @RestController).
Each DispatcherServlet has one Spring context its own. If you want some beans to be shared across your web application, it doesn't be achieved by registering beans on the DispatcherServlet context.
In that case, you can register your beans on the context included in ContextLoaderListener, which is so called bootstrap context since it is root of Spring contexts of web application. DispatcherServlet contexts are children of the bootstrap context. For a beans in parent context, it is visible to the child context, but not vice versa.
Once you register your beans into the bootstrap context in ContextLoaderListener, your DispatcherServlet can access the beans.

Registering ContextLoaderListener in web.xml:

<listener>
    <listner-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<!-- By default, ContextLoaderListener uses XmlWebApplicationContext

<context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
</context-param>

-->

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring-config/context-*.xml</param-value> <!-- For instance -->
</context-param>
Enter fullscreen mode Exit fullscreen mode

ContextLoaderListener uses ServletContext to get the information where the metadata was placed.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay