SoFunction
Updated on 2025-04-14

Configuring ContextLoaderListener method in Spring

Configuring ContextLoaderListener in Spring

  <!-- contextConfigLocationParameters are used to specifySpringConfiguration file needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-persist-*.xml</param-value>
    </context-param>

    <!-- ConfigurationspringCore listener Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class></listener-class>
    </listener>

What is the function of ContextLoaderListener?

The function of ContextLoaderListener is to read the xml file defined in contextConfigLocation when starting the web container, automatically assemble the configuration information of the ApplicationContext, and generate the WebApplicationContext object, and then place this object in the ServletContext property. In this way, as long as we get the Servlet, we can get the WebApplicationContext object, and use this object to access the bean managed by the spring container.

Simply put, the above configuration provides spring support for the project and initializes the Ioc container.

Can ContextLoaderListener be configured without configuration?

  • If there is only one Servlet of Spring mvc, listener can be ignored.
  • However, if Shiro etc. is used, the Spring configuration used by Shiro must be loaded in the listener.
  • Generally, the Spring configuration of Dao and Service will be loaded in the listener because it may be used in multiple servlets, and there is a visibility problem between the parent-child Context. Therefore, in order to prevent duplicate loading, it is necessary to load in the listener.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.