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 是我的项目名称

原文地址:https://www.cnblogs.com/liuchao102/p/4431539.html