利用ServletContextListener 獲取spring上下文

你的需求是當服務器啓動後加載一些數據,我們就可以使用ServletContextListener來滿足需求
傳統方式

app = new ClassPathXmlApplicationContext("xxx.xml");  

這樣獲取是不可以的,當j2ee容器啓動後會或獲取一次spring上下文,如果使用該方式會在一次獲取上下文。自己想想就知道.

ServletContextListener 不受spring管理我們應該如何獲取呢?

實際上spring同樣使用了ServletContextListener接口,我們可以通過實現一個自己的ServletContextListener
來得到spring上下文
代碼如下:

package com.xiaomaha.config;  

import java.util.List;  

import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;  

import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  

public class InitialData implements ServletContextListener {  

    private static List dataList;  

    private ApplicationContext app;  

    public static List getDataList() {  
        return dataList;  
    }  

    public static void setDataList(List dataList) {  
        InitialData.dataList = dataList;  
    }  

    public void contextDestroyed(ServletContextEvent arg0) {  
        // TODO Auto-generated method stub  

    }  

    public void contextInitialized(ServletContextEvent event) {  

        app = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); //獲取spring上下文!  
        app.getBean("UserService"); //獲取到bean了,你就可以任意搞它了,想怎麼搞就怎麼搞  
        .............  
        //!最後得到的數據傳遞給dataList引用就O了!  
    }  

}  

然後在web.xml配置一句

<listener>  
    <listener-class>  
        包+類名  
    </listener-class>  
</listener>  

好了自己寫一個類,在構造函數(一般spring都是配置構造函數,當然你也可以使用其它方法)裏打印一句話,你可以看看服務器啓動後是否會執行兩次?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章