JAVA獲取Spring上下文


1. 添加監聽

public class SpringContextListener implements ServletContextListener {
    //獲取spring注入的bean對象  
    public static WebApplicationContext springContext; 
    public void contextDestroyed(ServletContextEvent event) {
        //springContext = null;
    }
    /**
     * 獲取spring上下文
     */
    public void contextInitialized(ServletContextEvent event) {
        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
    }
}

2. 在web.xml中配置監聽

<listener>  
     <listener-class>com.test.util.SpringContextListener</listener-class>
</listener>

3. 使用

獲取ServletContext
SpringContextListener.springContext.getServletContext()
獲取webapp路徑
String webPath = SpringContextListener.springContext.getServletContext().getRealPath("");

    獲取到的路徑 /usr/local/tomcat/webapps/multimedia

    multimedia 是我的項目名稱

 


免責聲明!

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



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