关于在基于spring的框架中使用static 方法的问题
一般使用spring做框架设计的web 应用中,都是利用Webapplicationcontext这个类做为beanFactory的。而这个类是在启动时加载的。
在应用中可能会有一些helper,或则util类,需要提供静态方法来获取数据,不如DeptHelper.treeListDept()。如果该类要从一个DAO里取数据,那么它该如何访问ioc的beanFactory,以获取这个DAO对象呢?
大家知道WebApplicationContext一般是通过WebApplicationContextUtils
.getRequiredWebApplicationContext(config.getServletContext());来获取的。但是如果我们的DeptHelper.treeListDept()不能获取一个HttpServletRequest或则ServletContext,该怎么办呢?
我想了个办法,就是写一个静态类
ApplicationContextKeeper ,如下:
private static ApplicationContext appCtx = null;
public static ApplicationContext getAppCtx() {
return appCtx;
}
public static void init(ApplicationContext ctxVal) {
appCtx = ctxVal;
}
这个类在系统启动时由一个servlet来初始化(就是调用它的init),例如:
public class ApplicationContextLoadServ extends BaseServ {
public void init(ServletConfig servletConfig) throws ServletException {
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(servletConfig.getServletContext());
ApplicationContextKeeper.init(ctx);
}
public void destroy() {
super.destroy();
}
}
该servlet的启动顺序是在spring的ContextLoaderServlet之后的,这样就保证获取了ApplicationContext。
这样的话我的
DeptHelper.treeListDept()就可以这样写了
{
IDeptInfoDAO deptInfoDAO = (IDeptInfoDAO)ApplicationContextKeeper.getAppCtx().getBean("deptInfoDAO");
deptInfoDAO.listDeptData.....
}
当然我是初次应用,想来也不会有什么问题。大家可以讨论讨论