简体   繁体   English

Spring @Async和Java CompleteFuture提供异步:在异步方法内调用bean

[英]Spring @Async and java CompleteFuture supply async: call bean inside asynchronous method

I need to make an asynchronous call to a service which is injected by Spring using the autowire annotation. 我需要异步调用由Spring使用自动装配注解注入的服务。 I'm doing something like this 我正在做这样的事情

@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: 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();
} 

The Error I'm getting says the following: 我收到的错误信息如下:

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

If I understand the problem correctly I think that Spring injects a proxy when does dependency injection so the serviceName bean is not available in the scope of the asyncCall, is that correct? 如果我正确理解了这个问题,我认为Spring在依赖项注入时注入了一个代理,因此serviceName bean在asyncCall的范围内不可用,对吗?

I tried creating a new class only for the asyncMethod using prototype scope so it can be created any time is been call, and added as a bean on the listenerclass but this didnt work also. 我尝试使用原型范围仅为asyncMethod创建一个新类,以便可以在调用任何时间创建它,并将其作为bean添加到listenerclass上,但这也没有用。

Which workarounds could I use to manage this situation? 我可以使用哪些变通办法来解决这种情况?

Best regards 最好的祝福

CompletableFuture.supplyAsync will run your method in a pooled thread. CompletableFuture.supplyAsync将在池化线程中运行您的方法。

That thread is completely does not received @Transaction around. 该线程是完全没有收到@Transaction周围的。

So you have to create and common/rollback your transaction manually 因此,您必须手动创建并通用/回滚交易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM