web项目启动时进行数据的预加载(servlet获得spring的bean)

本文介绍了一种在Servlet启动时加载数据至内存的方法,以提高频繁使用的数据访问效率。通过在web.xml中配置servlet的`load-on-startup`属性,实现数据在服务启动时的预加载。注意,由于servlet和Spring管理的bean不在同一容器中,获取Spring容器中的bean需要使用特定的工具方法。

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

有些数据,变动量不大,大事使用比较频繁,所以想放在服务启动时,就讲数据加载到内存中,方便在程序中进行取用。

 

用到了一个简单的实现方法。新建一个servlet,在servlet的init()方法中,进行数据的加载。在web.xml中配置,servlet在启动时加载就行了。

具体实现如下:

 

servlet 代码:

 

 

public class InitData2MemServlet extends HttpServlet {

	private NodeManagerService nodeManagerService;
	
	@Override
	public void init() throws ServletException {
		super.init();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		nodeManagerService = (NodeManagerService)wac.getBean("nodeManagerService");
		nodeManagerService.getNode2Map(new HashMap<String, Object>(), SystemMem.nodeMap);
	}

}

 

web.xml 中配置 <load-on-startup>2</load-on-startup> 就可以了。

 

此处需要注意的就是在servlet中使用 spring的注解进行注入是无效的,原因servlet 和 spring管理的bean不在一个容器中。servlet是在webcontext容器中。而spring的bean是在Spring容器中。

 

所以此处通过下面这段代码,来获得spring容器中的bean。

 WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

nodeManagerService = (NodeManagerService)wac.getBean("nodeManagerService");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值