首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试从applicationContext获取bean时,获取未初始化或已关闭的BeanFactory

尝试从applicationContext获取bean时,获取未初始化或已关闭的BeanFactory
EN

Stack Overflow用户
提问于 2013-05-15 20:34:52
回答 2查看 1.2K关注 0票数 0

我正在使用JDKtimer(在spring项目中)重新加载bean方法来刷新元数据值。我编写了以下代码行来获取bean。

代码语言:javascript
复制
 Long schedulerDelayTime  = AppParametersHelper.getLong(SCHEDULER_DELAY_TIME);
 Long schedulerRepeatTime = AppParametersHelper.getLong(SCHEDULER_REPEAT_TIME);
 ApplicationContext ctx = ApplicationContextUtil.getContext();
 IPartyRequestDataCache partyRequestPingService = 
(IPartyRequestDataCache) ctx.getBean("partyRequestDataCache");
 partyRequestPingService.refreshDataCache();

JDK定时器是这样调用的

代码语言:javascript
复制
TimerTask partyRequestSchedulertask = new DataCacheRefreshScheduler();
Timer timer = new Timer(); 
timer.schedule(partyRequestSchedulertask,
                           schedulerDelayTime,
                           schedulerRepeatTime);

我得到了以下异常

代码语言:javascript
复制
    Exception in thread "Timer-2" java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'ref
resh' before accessing beans via the ApplicationContext
    at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicat
ionContext.java:171)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1045)
    at org.tiaa.partyrequest.listener.DataCacheRefreshScheduler.run(DataCacheRefreshScheduler.java:20)
    at java.util.TimerThread.mainLoop(Timer.java:512)
    at java.util.TimerThread.run(Timer.java:462)

在控制台中打印此错误后,它将执行refreshDataCache()。我可以使用try和catch块来捕获这个错误,但是有没有办法避免这个错误。为什么会发生这种情况?

还有另一种使用spring-servlet.xml文件实现JDK计时器的方法,但是这里我不能从文件中传递repeatInterval和startDelay的值。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-21 17:34:13

感谢您的支持。我无法纠正这个错误,事实上我已经改变了我的方法。我使用了带有spring方法的JDK计时器。您可以在下面的spring文档Spring documentation for JDK timer中找到“使用JDK计时器支持”这个短语。

因为我想使用属性文件来控制延迟和周期时间,所以我使用了

代码语言:javascript
复制
<context:property-placeholder location="classpath:partyrequestws/Timer.properties"/>

这解决了我在第一次调用计时器时获得异常的问题。

我希望这会对你有所帮助。如果任何人感兴趣,我会张贴整个代码库坚果,它是非常直接的。

谢谢。

票数 0
EN

Stack Overflow用户

发布于 2013-05-16 17:51:54

尝试在@PostCounstuct方法中运行此代码,此时所有spring bean都应该已初始化。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16565143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档