Spring在Listener中注入bean的问题
Spring在Listener中注入bean的问题
蜡笔小小小新 发表于1年前
Spring在Listener中注入bean的问题
  • 发表于 1年前
  • 阅读 84
  • 收藏 2
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

摘要: 在基于Spring的项目中,有时我们在写Listsener的时候需要把Spring IOC容器管理的一个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)  { 
    }
	
}

 

标签: Java Spring
共有 人打赏支持
粉丝 28
博文 112
码字总数 79661
×
蜡笔小小小新
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: