服务内部的Spring @Async方法 [英] Spring @Async method inside a Service
问题描述
我有一个带有同步方法的Service Bean,该同步方法调用了内部异步方法:
I have this Service bean with a sync method calling an internal async method:
@Service
public class MyService {
public worker(){
asyncJob();
}
@Async
asyncJob(){
...
}
}
麻烦的是asyncJob并不是真的以异步方式调用. 我发现这不起作用,因为内部呼叫会跳过 AOP代理.
The trouble is that the asyncJob is not really call in async way. I found that this doesn't work because an internal call skips the AOP proxy.
所以我尝试自我介绍:
@Service
public class MyService {
MyService mySelf;
@Autowired
ApplicationContext cnt;
@PostConstruct
public init(){
mySelf=(MyService)cnt.getBean("myService");
}
public worker(){
mySelf.asyncJob();
}
@Async
asyncJob(){
...
}
}
失败.再次没有异步调用.
It fails. Again no async call.
所以我尝试将其划分为两个豆:
@Service
public class MyService {
@Autowired
MyAsyncService myAsyncService;
public worker(){
myAsyncService.asyncJob();
}
}
@Service
public class MyAsyncService {
@Async
asyncJob(){
...
}
}
再次失败.
唯一的工作方法是从 Controller Bean 调用它:
The only working way is to call it from a Controller Bean:
@Controller
public class MyController {
@Autowired
MyAsyncService myAsyncService;
@RequestMapping("/test")
public worker(){
myAsyncService.asyncJob();
}
}
@Service
public class MyAsyncService {
@Async
public asyncJob(){
...
}
}
但是在这种情况下,这是一项服务工作……为什么我不能从服务中调用它?
But in this case it is a service job... why I can not call it from a Service?
推荐答案
我解决了第三个方法(将其分为两个bean),将异步方法修改器切换为 public
I solved the third method (divide it in two beans) switching Async method modifier to public
@Service
public class MyService {
@Autowired
MyAsyncService myAsyncService;
public worker(){
myAsyncService.asyncJob();
}
}
@Service
public class MyAsyncService {
@Async
public asyncJob(){ // switched to public
...
}
}
这篇关于服务内部的Spring @Async方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!