Spring在Listener中注入bean的问题

下面是我第一次这么干的时候:

package com.lin.warehouse.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.lin.warehouse.service.IWarehouseService;
import com.lin.warehouse.service.impl.WarehouseServiceImpl;

@WebListener
public class TestListener implements HttpSessionListener {
	
	@Autowired
	private IWarehouseService warehouseService;

    public void sessionCreated(HttpSessionEvent event)  { 
    	
    	System.out.println("----------------------------------------------------->"+warehouseService.getClass().toString());
    }

    public void sessionDestroyed(HttpSessionEvent event)  { 
    }
	
}

在一个Listsner中把接口的实例注入进来,但这样得不到接口的实例,接口引用是空指针。为什么会这样呢?因为Listsner是由Tomcat管理的,Tomcat无法把SpringIOC容器的Bean诸如到Listsner,而注入Bean的工作是由Spring负责的。那么解决这个问题呢?

Spring容器实现了一个监听ServletContext启动事件的监听器,这个监听器把一个IOC容器在ServletContext启动时放进ServletContext容器当做应用的Bean容器。现在只需要在Listsner中得到这个IOC容器就可以了,看看org.springframework.web.context.ContextLoaderListener的源代码。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		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!");
		}

		Log logger = LogFactory.getLog(ContextLoader.class);
		servletContext.log("Initializing Spring root WebApplicationContext");
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			// Store context in local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				if (!cwac.isActive()) {
					// The context has not yet been refreshed -> provide services such as
					// setting the parent context, setting the application context id, etc
					if (cwac.getParent() == null) {
						// The context instance was injected without an explicit parent ->
						// determine parent for root web application context, if any.
						ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
					}
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

			ClassLoader ccl = Thread.currentThread().getContextClassLoader();
			if (ccl == ContextLoader.class.getClassLoader()) {
				currentContext = this.context;
			}
			else if (ccl != null) {
				currentContextPerThread.put(ccl, 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;
		}
	}

上面是初始化ServletContext的方法,把IOC容器放进ServletContext容器的是这句,

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

它的KEY是 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,那就在Listsner中通getAttribute(“”,);方法得到IOC容器

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.lin.warehouse.service.IWarehouseService;
import com.lin.warehouse.service.impl.WarehouseServiceImpl;

@WebListener
public class TestListener implements HttpSessionListener {
	
	//@Autowired
	private IWarehouseService warehouseService;

    public void sessionCreated(HttpSessionEvent event)  { 
    	
    	ApplicationContext applicationContext = (WebApplicationContext)event.getSession().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    	
    	warehouseService = applicationContext.getBean("warehouseService",WarehouseServiceImpl.class );
    }

    public void sessionDestroyed(HttpSessionEvent event)  { 
    }
	
}

 

转载于:https://my.oschina.net/ChiLin/blog/754468

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值