spring ContextLoaderListener

本文深入探讨了如何在Web应用中初始化WebApplicationContext,并详细解释了如何从ServletContext中获取ApplicationContext,进而通过ApplicationContext实例访问Spring配置文件中的Bean。通过示例代码,展示了如何在Servlet环境中实现ApplicationContext的自动装配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们要自动装配ApplicationContext配置信息时候,首先在web.xml配置ContextLoaderListener,下面是部分源代码:
[java] 
public class ContextLoaderListener implements ServletContextListener { 
 
    private ContextLoader contextLoader; 
 
 
    /**
     * Initialize the root web application context.
     */ 
    public void contextInitialized(ServletContextEvent event) { 
        this.contextLoader = createContextLoader(); 
        this.contextLoader.initWebApplicationContext(event.getServletContext());//注意此处 
    } 
 
    protected ContextLoader createContextLoader() { 
        return new ContextLoader(); 
    } 
 
    public ContextLoader getContextLoader() { 
        return this.contextLoader; 
    } 
 
    public void contextDestroyed(ServletContextEvent event) { 
        if (this.contextLoader != null) { 
            this.contextLoader.closeWebApplicationContext(event.getServletContext()); 
        } 
    } 
 

我们主要了解下WebApplicationContext是怎么初始化出来的,首先contextInitialized(ServletContextEvent event)方法的this.contextLoader.initWebApplicationContext(event.getServletContext());进去之后我们看到
[java]
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) 
        throws IllegalStateException, BeansException { 
 
    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { 
        throw new IllegalStateException( 
                "Cannot initialize context because there is already a root application context present - " + 
                "check whether you have multiple ContextLoader* definitions in your web.xml!"); 
    } 
 
    servletContext.log("Initializing Spring root WebApplicationContext"); 
    if (logger.isInfoEnabled()) { 
        logger.info("Root WebApplicationContext: initialization started"); 
    } 
    long startTime = System.currentTimeMillis(); 
 
    try { 
        // Determine parent for root web application context, if any. 
        ApplicationContext parent = loadParentContext(servletContext); 
 
        // Store context in local instance variable, to guarantee that 
        // it is available on ServletContext shutdown. 
        this.context = createWebApplicationContext(servletContext, parent); 
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);//注意此处 
        currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this.context); 
 
        if (logger.isDebugEnabled()) { 
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + 
                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); 
        } 
        if (logger.isInfoEnabled()) { 
            long elapsedTime = System.currentTimeMillis() - startTime; 
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); 
        } 
 
        return this.context; 
    } 
    catch (RuntimeException ex) { 
        logger.error("Context initialization failed", ex); 
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); 
        throw ex; 
    } 
    catch (Error err) { 
        logger.error("Context initialization failed", err); 
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); 
        throw err; 
    } 

注意注意此处部分,说明当我们要得到一个WebApplicationContext只需要在ServletContext中获取属性名为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的常量值就可以得到一个ApplicationContext,最终可以获取spring配置文件中任意一个Bean对象
eg:
[java] 
public String execute() throws Exception { 
    // TODO Auto-generated method stub 
    ApplicationContext conn=(ApplicationContext)ServletActionContext.getServletContext().getAttribute(WebApplicationContext.class.getName() + ".ROOT"); 
    System.out.println(conn.getBean("biz")); 
    return SUCCESS; 

或者直接使用org.springframework.web.context.support.WebApplicationContextUtils这个抽象的工具类来获得WebApplicationContext,该类的方法
[java]
public static WebApplicationContext getWebApplicationContext(ServletContext sc) { 
    return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值