springboot @Async异步方法内调用其他bean,异步方法提前结束

测试代码

@SpringBootTest
class NatrpApplicationTests {
    
    @Autowired
    ReportService reportService;
    
    Report report = new Report();
    @Test
    void contextLoads() throws InterruptedException {
        report.setReportId(Long.valueOf("123456"));
        reportService.insertReport(report);  //异步方法
        System.out.println("主线程继续");
    }
}

异步方法

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Override
    @Async
    public void insertReport(Report report) {
        reportMapper.insertReport(report);      //代码执行到这里就会提前结束,这一行不会执行
        System.out.println("线程" + Thread.currentThread().getName());
    }
}

执行结果
主线程继续

  1. 看一下你启动类上有没有 @EnableAsync 注解
  2. 你的主线程结束的太快 , 异步方法还没来的急执行, 在你 System.out.println("主线程继续");
    这段代码之后 加上 Thread.sleep(1000 * 5); 别让主线程那么快结束

加日志,看看到底来了没

你这个主线程结束,整个进程都结束了,进程结束,所有的线程都没了