例外春季启动时间表

时间:2017-07-24 09:43:37

标签: spring multithreading spring-mvc spring-boot twitter

我制定了一个每5分钟执行一次的时间表 这是它

package com.start.services;
import ...    
@Component
public class ScheduledTasks { 
    @Autowired
    AlertServiceImpl alertServ ;
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 1000*60*5) // every 5 minutes
    public void reportCurrentTime() {

        log.info("Refreshing started at {}", dateFormat.format(new Date()));
        alertServ.refreshAlerts();

    }
}

但是当我执行推特服务时,我得到了这个奇怪的例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.twitter': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:192) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.sun.proxy.$Proxy105.searchOperations(Unknown Source) ~[na:na]

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为外部服务(例如您的 Twitter 集成)在“请求”范围内运行,但计划任务旨在在其他范围内运行,例如应用程序范围; spring 根据设计的选择,无法知道请求何时开始以及何时结束。但是有几个解决方案/变通方法,例如实现自定义 ResquestAttributes 和自定义作业 - 甚至自定义请求范围。

请参考这篇文章:https://medium.com/@pranav_maniar/spring-accessing-request-scope-beans-outside-of-web-request-faad27b5ed57

有关弹簧作用域的更多信息:https://www.baeldung.com/spring-bean-scopes