1. 程式人生 > >[Spring]web.xml中配置ContextLoaderListener監聽器的作用

[Spring]web.xml中配置ContextLoaderListener監聽器的作用

spring的核心配置檔案中,為什麼配置ContextLoaderListener監聽器

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

開啟ContextLoaderListener的原始碼,發現ContextLoaderListener實現了ServletContextListener介面

/*     */ public class ContextLoaderListener
extends ContextLoader /* */ implements ServletContextListener /* */ {
/* */ public ContextLoaderListener() /* */ { /* */ } /* */ /* */ public ContextLoaderListener(WebApplicationContext context) /* */ { /* 98 */ super(context); /* */ } /* */ /* */ public void
contextInitialized(ServletContextEvent event) /* */ { /* 106 */ initWebApplicationContext(event.getServletContext()); /* */ } /* */ /* */ public void contextDestroyed(ServletContextEvent event) /* */ { /* 115 */ closeWebApplicationContext(event.getServletContext()); /* 116 */ ContextCleanupListener.cleanupAttributes(event.getServletContext()); /* */
} /* */ }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

實現了ServletContextListener介面的作用就是當專案一經啟動,就會啟用實現了此介面的類方法,可以進行相關的初始化操作。 
ServletContextListener介面實現了 
public void contextInitialized(ServletContextEvent event)與 
public void contextDestroyed(ServletContextEvent event) 
兩個方法, 
意味著專案一經啟動,會進入contextInitialized方法中,進行Spring的相關配置。並且contextInitialized方法有ServletContext引數,可以在web.xml中配置引數,用來ServletContext讀取相關Spring配置檔案, 一般 Dao, Service 的 Spring 配置都會在 listener 里加載。 
專案退出時啟用contextDestroyed方法。

結尾:

1. 如果只有 Spring mvc 的一個 Servlet,listener 可以不用。
2. 但是如果用了Shiro 等,Shiro 用到的 Spring 的配置必須在 listener 里加載。
3. 一般 Dao, Service 的 Spring 配置都會在 listener 里加載,因為可能會在多個 Servlet 裡用到,
因為父子 Context 的可見性問題,防止重複載入所以在 listener 里加載。

所以,有時可用可不用,有時必用,具體看情況。