java - Spring @Async 和 java CompleteFuture 提供异步 : call bean inside asynchronous method

标签 java spring java-8

我需要对 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/

相关文章:

java - 在 Java 中复制 Arraylist 时出现异常

java - Google 安全浏览 v4 API java

java - 移动文件的替代方法

java - 何时或在什么情况下我应该使用Optional来检查null?

Java正则表达式检查字符串包含超过2个单词并且包含数字

java - Spring 启动测试 : context loaded for every test?

java - Spring STS : How to automatically create a webpage for all API methods, 就像 .Net 一样

java - 如何使用 Jersey/Spring 获取 pki 证书?

java - 使用 Streams 获取每个子部门和部门的员工,

java - 在 future list 上流式传输的最有效方式