任意位置得到Spring bean

来源:互联网 发布:java上下文是什么意思 编辑:程序博客网 时间:2024/06/06 01:26

public class org.springframework.web.context.ContextLoaderListener 

                                  extends org.springframework.web.context.ContextLoader 

                                                                implement javax.servlet.ServletContextListener {}


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

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:Spring-Hibernate.xml,classpath:Spring-beans.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

ContextLoaderListener继承了ContextLoader,而ContextLoader有这样一个方法:

/** * 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对象。

原创粉丝点击