首页 > 解决方案 > 创建名为“scopedTarget.userPlatform”的 bean 时出错:范围“用户”对当前线程不活动

问题描述

org.springframework.beans.factory.BeanCreationException:创建名为“scopedTarget.userPlatform”的bean时出错:范围“用户”对于当前线程不活动;如果您打算从单例中引用它,请考虑为该 bean 定义一个作用域代理;嵌套异常是 java.lang.IllegalStateException: Not in any context!在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) 在 org.springframework.aop.target .SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) 在 org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:705) 在 org.springframework.aop.framework。在 java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) 在 java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) 在 java.util 调用 (Executors.java:511)。 concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)在 java.lang.Thread.run(Thread.java:748) 引起:java.lang.IllegalStateException:不在任何上下文中!在 com.cumulocity.microservice.context.ContextServiceImpl.getContext(ContextServiceImpl.java:41) 在 com.cumulocity.microservice.context.annotation.EnableContextSupportConfiguration$2。

标签: spring-bootcumulocity

解决方案


使用 @Scheduled 注解运行一些代码时,您需要定义上下文。否则你会得到这个异常,因为使用 cumulocity API 的线程不在任何上下文中。

例如,对于所有订阅的租户:

private final MicroserviceSubscriptionsService subscriptions;

@Scheduled(fixedDelay = 5 * 60 * 1000)
private void checkForAgentRepresentation() {
    for (final MicroserviceCredentials mc : subscriptions.getAll()) {
        final String tenant = mc.getTenant();
        subscriptions.runForTenant(tenant, () -> {
            //doSomething like
            inventoryApi.get(...);
        });
    }
}

推荐阅读