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