`

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

 
阅读更多

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

 

用到了一个简单的实现方法。新建一个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");

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics