ContextLoaderListener和DispatcherServlet的contextConfigLocation區別


1.配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:META-INF/spring/**/*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springMvcDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath*:META-INF/springmvc/**/springmvc-*.xml
            </param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvcDispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

 

 

2.解析

存在兩個contextConfigLocation,一個是給ContextLoadrListener,一個是給DispatcherServlet。

都是用於加載上下文,一個是spring的,一個是springMVC的,其中ContextLoadrListener先加載,然后才是DispatcherServlet。

2.1 區別:

DispatcherServlet一般會加載MVC相關的bean配置管理(如: ViewResolver, Controller, MultipartResolver, ExceptionHandler, etc.)

ContextLoaderListener一般會加載整個Spring容器相關的bean配置管理(如: Log, Service, Dao, PropertiesLoader, etc.)

2.2 注意點:

 

    • 也就是如果我把@Controller的注解放到ContextLoadrListener中的配置文件去加載是不可以的,DispatcherServlet到時對這個controller會無感知。
    • DispatcherServlet的上下文僅僅是Spring MVC的上下文, 而ContextLoaderListener的上下文則對整個Spring都有效. 也就是DispatcherServlet可以使用spring的上下文,但是spring不能使用DispatcherServlet的上下文。一般Spring web項目中同時會使用這兩種上下文


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM