Spring 从applicationContext获取bean时,获取BeanFactory未初始化或已关闭

Spring 从applicationContext获取bean时,获取BeanFactory未初始化或已关闭,spring,Spring,我使用JDKtimer(在spring项目中)重新加载bean方法来刷新元数据值。我写了以下几行来取豆子 Long schedulerDelayTime = AppParametersHelper.getLong(SCHEDULER_DELAY_TIME); Long schedulerRepeatTime = AppParametersHelper.getLong(SCHEDULER_REPEAT_TIME); ApplicationContext ctx = ApplicationC

我使用JDKtimer(在spring项目中)重新加载bean方法来刷新元数据值。我写了以下几行来取豆子

 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定时器就是这样调用的

TimerTask partyRequestSchedulertask = new DataCacheRefreshScheduler();
Timer timer = new Timer(); 
timer.schedule(partyRequestSchedulertask,
                           schedulerDelayTime,
                           schedulerRepeatTime);
我得到了以下例外

    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-and-catch块捕获这个错误,但有没有办法避免这个错误。为什么会这样


还有另一种使用spring-servlet.xml文件执行JDK计时器的方法,但在这里我无法从文件中传递repeatInterval和startDelay的值。

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

感谢您的支持。我无法纠正错误,因为我改变了我的方法。我使用了JDK定时器和spring方法。您可以在下面的spring文档中查找“使用JDK定时器支持”这一短语

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

<context:property-placeholder location="classpath:partyrequestws/Timer.properties"/>

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

我希望这会有帮助。如果有人感兴趣,我将张贴整个代码的基础螺母,这是非常直接的


谢谢。

谢谢,我已经放置了此注释并尝试使用它,它为partyRequestDataCache bean引发空指针异常。为什么要使用ApplicationContextTil.getContext()。可能上下文配置有问题。尝试@Autowired IPartyRequestDataCache partyRequestDataCache;我也试过了。仍然有空指针异常。说到applicationContextUtil,配置仅是正确的。它给我带来了价值。如果我使用try-catch,就不会出现这个错误。但我想弄清楚为什么会这样。