1. 为什么会产生同一类内异步注解失效?
我们要清楚,异步,事务这些注解生效的原理,在于通过切面创建了代理类,通过操作代理类我们实现了异步,事务,但是当我们在同一类内声明异步,事务时,则不会创建代理类,因此异步,事务注解失效。
2. 如何解决失效问题?
有两种方式
一、在另一个类中定义异步方法,进行调用,略。
二、在同一个类中,通过自己注入自己的方式实现代理类的创建
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class OtherReportAsyncService {
@Lazy
@Autowired
private OtherReportAsyncService service;
/**
* 测试方法
*/
public void test(){
service.asyncMethod();
}
/**
* 异步方法
*/
@Async
public void asyncMethod(){
System.out.println("异步");
}
}