浏览 5137 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2005-06-17
public class AutoOrderResultProvider extends ResultProvider implements ApplicationContextAware { private static OperationHelper operationHelper ; private static ApplicationContext applicationContext ; public void setApplicationContext(ApplicationContext arg0); throws BeansException { applicationContext = arg0; } public void fillOperationHelper();{ otherClass = (otherClass); applicationContext .getBean("otherClass");; } 。。。。 } 在applicationContext.xml文件里注册了这个bean,在web.xml里注册了ContextLoaderListener,但如果有一段时间不访问web应用,applicationContext和operationHelper就会为null.不知道为什么?百思不得其解,难道是被GC了。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2005-06-17
spring有两种生命周期,如果一个bean声明成singleton的那么生命周期由spring管理,如果不是singleton的那么生命周期由自己的程序管理。如果是Singleton的那么在一个JVM中肯定是一直存在的。不过会出现你说的异常。你为生命要把OperationHelper 和
ApplicationContext 都声明成static的?去掉试试 |
|
返回顶楼 | |
发表时间:2005-06-17
设为静态是因为其它的类(命名为A)要调用这个类,但是A类是通过非spring的方法产生这个类的,所以我想设为静态的,不知这样是否可行。
|
|
返回顶楼 | |
发表时间:2005-06-17
那就对了,你在这个类里面声明了private static的OperationHelper 和ApplicationContext 也就是说这两个类的应用只在当前这个类的生命周期里面存在,你这个类被GC了,里面的两个变量当然也不存在了。只需要保持一个reference在你的类里面,不需要static。不知道行不行,不过最好你把AutoOrderResultProvider也配置成SpringBean,不然你不能用这种方式访问ApplicationContext.
|
|
返回顶楼 | |
发表时间:2005-06-17
一开始AutoOrderResultProvider我已经配置成SpringBean了,所以我想问AutoOrderResultProvider在web应用启动时被spring实例化后,会存在多久?
因为AutoOrderResultProvider里OperationHelper和ApplicationContext是两个静态的,其他被new出来的AutoOrderResultProvider依赖于最初那个实例的这两个静态变量。如果不设成静态的,那么其它的类就无法得到这两个变量。 |
|
返回顶楼 | |
发表时间:2005-06-17
Raistlin 写道 一开始AutoOrderResultProvider我已经配置成SpringBean了,所以我想问AutoOrderResultProvider在web应用启动时被spring实例化后,会存在多久?
因为AutoOrderResultProvider里OperationHelper和ApplicationContext是两个静态的,其他被new出来的AutoOrderResultProvider依赖于最初那个实例的这两个静态变量。如果不设成静态的,那么其它的类就无法得到这两个变量。 如果AutoOrderResultProvider是SpringBean,并且你没有指定是非Singleton的,那么Spring就会一直在JVM中使用一个Instance。 我觉得你可以试试这样设计,其实你没有必要让Provider hold住一个AppContext,而是设计一个专门用来从Spring的配置文件里面load config,进行初始化的一个工具类: public class AppContextHelper{ private static ApplicationContext appCtx= null; public static Object getBean(String beanName);{ if(appCtx == null);{ //load the spring config //init the application context } return appCtx.getBean(beanName);; } } 然后在你的方法里面调用: otherClass = (otherClass) AppContextHelper.getBean("otherClass"); 假设你是在Servlet里面需要获取SpringBean的实例,你可以用WebApplicationContext来获取Instance. |
|
返回顶楼 | |
发表时间:2005-06-18
好办法,谢谢阿木欢。
|
|
返回顶楼 | |