ContextLoaderListener or not? ContextLoaderListener or not? java java

ContextLoaderListener or not?


In your case, no, there's no reason to keep the ContextLoaderListener and applicationContext.xml. If your app works fine with just the servlet's context, that stick with that, it's simpler.

Yes, the generally-encouraged pattern is to keep non-web stuff in the webapp-level context, but it's nothing more than a weak convention.

The only compelling reasons to use the webapp-level context are:

  • If you have multiple DispatcherServlet that need to share services
  • If you have legacy/non-Spring servlets that need access to Spring-wired services
  • If you have servlet filters that hook into the webapp-level context (e.g. Spring Security's DelegatingFilterProxy, OpenEntityManagerInViewFilter, etc)

None of these apply to you, so the extra complexity is unwarranted.

Just be careful when adding background tasks to the servlet's context, like scheduled tasks, JMS connections, etc. If you forget to add <load-on-startup> to your web.xml, then these tasks won't be started until the first access of the servlet.


You can configure the application context the other way around as well. E.g. in order to make the OpenEntityManagerInViewFilter work. Setup the ContextLoaderListener and then configure your DispatcherServlet with:

<servlet>    <servlet-name>spring-mvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value></param-value>    </init-param></servlet>

Just make sure that the contextConfigLocation parameter value is empty.


I want to share what I've done on my Spring-MVC application:

  1. On the we-mvc-config.xml I added just the classes annotated with @Controller:

    <context:component-scan base-package="com.shunra.vcat">    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/></context:component-scan>
  2. On the applicationContext.xml files I added all the rest:

    <context:component-scan base-package="com.shunra.vcat">    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/></context:component-scan>