我需要对Spring使用autowire注释注入的服务进行异步调用。 我正在做这样的事情
@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会在依赖注入时注入代理,因此serviceName bean在asyncCall的范围内不可用,这是正确的吗?
我尝试仅使用原型范围为asyncMethod创建一个新类,因此可以在调用时随时创建它,并将其作为bean添加到listenerclass上,但这也不起作用。
我可以使用哪些变通方法来管理这种情况?
祝你好运
答案 0 :(得分:0)
CompletableFuture.supplyAsync
将在池中运行您的方法。
该线程完全没有收到@Transaction
。
因此,您必须手动创建和共享/回滚您的交易