Web项目启动初始化监听器如何获取spring bean

我们在项目开发中可能会遇到这样的需求,在项目启动的时候我们通过web.xml配置加载一个监听器,然后在监听器中初始化我们项目中所需要的数据,那我们分析一下实现


1: 首先创建监听器,实现javax.servlet.ServletContextListener

public class InitDataListener implements ServletContextListener{
	
	//商品管理service
	private ProductService productService;

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//1:获取业务逻辑类查询商品信息
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//初始化 productService
		
	}

}

1.2:在web.xml配置监听器,不配置监听器是不起作用的

  <!-- 配置初始化数据的监听器 -->
    <listener>
  	<listener-class>cn.it.shop.listener.InitDataListener</listener-class>
  </listener>
*注意事项:cn.it.shop.listener.InitDataListener 一定要注册在org.springframework.web.context.ContextLoaderListener的后面,因为方案2,3,是在spring中获取容器的,所以要先执行ContextLoaderListener,在执行我们自己的InitDataListener 


2:我们要初始化数据,必须要获取到 productService 查询数据,那我们如何在这里获取spring注入的bean呢?

2.1:解决方案一:

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//解决方案1:以测试的思路解决此问题
			//1.1:创建Spring容器
		ApplicationContext context = new 
					ClassPathXmlApplicationContext("applicationContext-*.xml");
			//1.2:获取bean
		productService = (ProductService) context.getBean("productService");
			//1.3:输出测试
		System.out.println("===bean获取成功===="+productService);
	}

输出日志如下:

-----sendAction-----
this代表当前对象调用构造函数对象cn.it.shop.service.impl.AccountServiceImpl@285896a2
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Account>
获取到class泛型 ===class cn.it.shop.model.Account
this代表当前对象调用构造函数对象cn.it.shop.service.impl.CategoryServiceImpl@1cfd5850
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Category>
获取到class泛型 ===class cn.it.shop.model.Category
this代表当前对象调用构造函数对象cn.it.shop.service.impl.ProductServiceImpl@14da0969
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Product>
获取到class泛型 ===class cn.it.shop.model.Product

-----sendAction-----
this代表当前对象调用构造函数对象cn.it.shop.service.impl.AccountServiceImpl@774426c4
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Account>
获取到class泛型 ===class cn.it.shop.model.Account
this代表当前对象调用构造函数对象cn.it.shop.service.impl.CategoryServiceImpl@41269505
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Category>
获取到class泛型 ===class cn.it.shop.model.Category
this代表当前对象调用构造函数对象cn.it.shop.service.impl.ProductServiceImpl@4c019cad
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Product>
获取到class泛型 ===class cn.it.shop.model.Product

===bean获取成功====cn.it.shop.service.impl.ProductServiceImpl@4c019cad


我们从日志的输出可以看出问题,bean输出了两次,并且可以看出每一个都开辟了新的地址,由此可以得出,bean被创建了多次,虽然如此,但是我们的问题解决了没有?解决了,我们看蓝色字体部分,输出===bean获取成功====cn.it.shop.service.impl.ProductServiceImpl@4c019cad,这是我们监听中输出的吧,那这样我们的问题解决了,但是这样并不推荐使用, 不可取,因为会把Spring配置文件加载两次 


2.2 解决方案2:

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//解决方案2:直接到ServletContext中获取Spring配置文件
			//2.1:获取Spring容器
		ApplicationContext context = (ApplicationContext) sce.getServletContext()
						.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
			//2.2:获取bean
		productService = (ProductService) context.getBean("productService");
			//2.3:输出测试
		System.out.println("===bean获取成功===="+productService);
	}


日志输出:

-----sendAction-----
this代表当前对象调用构造函数对象cn.it.shop.service.impl.AccountServiceImpl@12436c64
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Account>
获取到class泛型 ===class cn.it.shop.model.Account
this代表当前对象调用构造函数对象cn.it.shop.service.impl.CategoryServiceImpl@1fe8c96d
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Category>
获取到class泛型 ===class cn.it.shop.model.Category
this代表当前对象调用构造函数对象cn.it.shop.service.impl.ProductServiceImpl@626b0fe0
获取当前this对象的父类信息class cn.it.shop.service.impl.BaseServiceImpl
获取当前this对象的父类信息(包括泛型信息)cn.it.shop.service.impl.BaseServiceImpl<cn.it.shop.model.Product>
获取到class泛型 ===class cn.it.shop.model.Product

===bean获取成功====cn.it.shop.service.impl.ProductServiceImpl@626b0fe0

这次我们可以清楚的看出,Spring配置文件只加载了一次,我们是直接获取已经加载好的配置文件,拿到我们所需要的bean,那你可能还在想要写这么多代码,实际上这只是介绍一下流程,终极解决方案在解决方案3


2.3终极解决方案3:

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//解决方案3:通过工具类加载即可
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
		productService = (ProductService) webApplicationContext.getBean("productService");
		System.out.println("===bean获取成功===="+productService);
	}

此解决方案为最终解决方案,这里就不查看日志了,肯定是对的,为什么我这么肯定,想知道原理的童鞋可以往下看

2.4WebApplicationContextUtils获取Spring容器的原理其实就是方案2,我们来看一下getWebApplicationContext这个方法

	public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
		return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	}
可以看到什么,细心的同学肯定已经看到了,是不是这个key呀 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 和我们方案2调用的key一样吧,我们再往下看这个方法getWebApplicationContext 

	public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
		Assert.notNull(sc, "ServletContext must not be null");
		Object attr = sc.getAttribute(attrName);
		if (attr == null) {
			return null;
		}
		if (attr instanceof RuntimeException) {
			throw (RuntimeException) attr;
		}
		if (attr instanceof Error) {
			throw (Error) attr;
		}
		if (attr instanceof Exception) {
			throw new IllegalStateException((Exception) attr);
		}
		if (!(attr instanceof WebApplicationContext)) {
			throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
		}
		return (WebApplicationContext) attr;
	}

看到这里应该就很清晰了吧,他做的事情和我们方案2做的事情一样,只不过他做了很多验证,最后返回WebApplicationContext,那有的同学可能说我们上边返回的是ApplicationContext,其实WebApplicationContext就是ApplicationContext的子级

	public interface WebApplicationContext extends ApplicationContext {
		//...
	}


OK分析完毕 end

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值