随意位置得到Spring bean

任意位置得到Spring beanpublic class org.springframework.web.context.ContextLoaderListenerextends or

任意位置得到Spring bean

public class org.springframework.web.context.ContextLoaderListener 

                                  extends org.springframework.web.context.ContextLoader 

                                                                implement javax.servlet.ServletContextListener {}


当结合Spring的时候我们首先要在web.xml启动Spring容器,所以会做如下配置:

/** * Obtain the Spring root web application context for the current thread * (i.e. for the current thread's context ClassLoader, which needs to be * the web application's ClassLoader). * @return the current root web application context, or <code>null</code> * if none found * @see org.springframework.web.context.support.SpringBeanAutowiringSupport */public static WebApplicationContext getCurrentWebApplicationContext() {return (WebApplicationContext) currentContextPerThread.get(Thread.currentThread().getContextClassLoader());}

通过这个方法可以在任何地方得到WebApplicationContext,从而得到任意一个已注入的bean对象。