在ServletContextListener中使用Spring管理的bean

package com.tang.back.web.listener;

import java.util.List;
import java.util.Map;

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

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tang.back.dto.sys.DictionaryDetail;
import com.tang.back.impl.service.DictionaryServiceImpl;

/**
 * 獲取系統字典數據,緩存在Application中以提高頁面初始化性能
 *
 * @author tang
 * @see [相關類/方法](可選)
 * @since [產品/模塊版本] (可選)
 */
public class DataCacheListener implements ServletContextListener{
    
    private final static String DICTIONARY_CACHE = "dictionary";
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); // 關鍵代碼
        final DictionaryServiceImpl dictionaryService = (DictionaryServiceImpl)springContext.getBean("dictionaryService"); // 關鍵代碼
        
        ServletContext application = sce.getServletContext();
        Map<String, List<DictionaryDetail>> dict = dictionaryService.getAllDictionary();
        application.setAttribute(DICTIONARY_CACHE, dict);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        application.removeAttribute(DICTIONARY_CACHE);
    }

    
}


上面的解決方案來自於stackoverflow:http://stackoverflow.com/questions/4746041/spring-injecting-a-dependency-into-a-servletcontextlistener


這裏是另一個獲得贊同數最多的答案,沒細研究,記錄在這裏。

@Autowired private Properties props;

@Override
public void contextInitialized(ServletContextEvent sce) {
    WebApplicationContextUtils
        .getRequiredWebApplicationContext(sce.getServletContext())
        .getAutowireCapableBeanFactory()
        .autowireBean(this);

    //Do something with props
    ...
}    


發佈了40 篇原創文章 · 獲贊 6 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章