1. 程式人生 > 實用技巧 >在Servlet(或者Filter,或者Listener)中使用spring的IOC容器

在Servlet(或者Filter,或者Listener)中使用spring的IOC容器

>>> hot3.png

web.xml中的載入順序為:listener >> filter >> servlet >> spring。其中filter的執行順序是filter- mapping在web.xml中出現的先後順序。

載入順序會影響對spring bean的呼叫。比如filter 需要用到bean ,但是載入順序是先載入filter 後加載spring,則filter中初始化操作中的bean為null。所以,如果過濾器中要使用到 bean,可以將spring 的載入改成Listener的方式。

<context-param>

<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext的配置資訊。

如果在web.xml中不寫任何引數配置資訊,預設的路徑是"/WEB-INF/applicationContext.xml",在WEB-INF目錄下建立的xml檔案的名稱必須是applicationContext.xml。如果是要自定義檔名可以在web.xml里加入contextConfigLocation這個context引數。

private static ApplicationContext ctx = null;
public Object getBean(String name) {
if (ctx == null) {
ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext);

}
return ctx.getBean(name);
}

原文地址

轉載於:https://my.oschina.net/sskxyz/blog/714616