服务中的Spring @Async方法


问题内容

我的Service Bean带有一个同步方法,该同步方法调用了内部异步方法:

@Service
public class MyService {

    public worker(){
        asyncJob();
    }

    @Async
    asyncJob(){
        ...
    }

}

问题在于asyncJob并不是真的以异步方式调用。我发现这是行不通的,因为内部调用会跳过 AOP代理

因此,我尝试 自引用 Bean:

@Service
public class MyService {

    MyService mySelf;
    @Autowired
    ApplicationContext cnt;
    @PostConstruct
    public init(){
        mySelf=(MyService)cnt.getBean("myService");
    }


    public worker(){
        mySelf.asyncJob();
    }

    @Async
    asyncJob(){
        ...
    }

}

它失败了 。再次没有异步调用。

因此,我尝试 将其 分为两个bean:

@Service
public class MyService {
    @Autowired
    MyAsyncService myAsyncService;
    public worker(){
        myAsyncService.asyncJob();
    }
}

@Service
public class MyAsyncService {

    @Async
    asyncJob(){
        ...
    }

}

再次失败

唯一的工作方法是从 Controller Bean 调用它:

@Controller
public class MyController {
    @Autowired
    MyAsyncService myAsyncService;
    @RequestMapping("/test")
    public worker(){
        myAsyncService.asyncJob();
    }
}

@Service
public class MyAsyncService {

    @Async
    public asyncJob(){
        ...
    }

}

但是在这种情况下,这是一项服务工作……为什么我不能从服务中调用它?


问题答案:

我解决了第三个方法(将其分为两个Bean),将Async方法修改器切换为 public

@Service
public class MyService {
    @Autowired
    MyAsyncService myAsyncService;
    public worker(){
        myAsyncService.asyncJob();
    }
}

@Service
public class MyAsyncService {

    @Async
    public asyncJob(){ // switched to public
        ...
    }

}