我需要对 Spring 使用 Autowiring 注释注入(inject)的服务进行异步调用。 我正在做这样的事情
@Component
Public class nameListener implements ApplicationListener<ContextRefreshEvent>{
@Autowire
protected ServiceName serviceName;
@Override
@Transactional
public onApplicationEvent(ContextRefreshEvent event){
log(asyncMethod.get().longValue());
}
@Async
public CompletableFuture<Long> asyncMethod(){
CompletableFuture<Long> result = CompletableFuture.supplyAsync(()-> serviceName.methodName());
return result;
}
serviceBean配置:
@Configuration
public class serviceClassConfiguration{
@Autowired
protected serviceFactory;
@Bean
public ServiceType serviceName();
//this only creates the type with the attributes it need
return serviceFactory.createServiceName();
}
我收到的错误如下:
org.springframework.beans.factory.BeanCreationException;
Scope session 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;
In this case, use RequestContextListener or RequestContextFilter to
expose the current request
如果我正确地理解了这个问题,我认为 Spring 在进行依赖注入(inject)时会注入(inject)一个代理,因此 serviceName bean 在 asyncCall 的范围内不可用,这是正确的吗?
我尝试使用原型(prototype)范围仅为 asyncMethod 创建一个新类,以便可以在任何时候调用它,并将其添加为监听器类上的 bean,但这也不起作用。
我可以使用哪些解决方法来处理这种情况?
致以诚挚的问候
最佳答案
CompletableFuture.supplyAsync
将在池线程中运行您的方法。
该线程完全没有收到 @Transaction
周围。
因此您必须手动创建并公用/回滚您的事务
关于java - Spring @Async 和 java CompleteFuture 提供异步 : call bean inside asynchronous method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514550/