spring中的异步方法@Async失效的原因有哪些,代码演示

1.没有在配置类中开启@EnableAsync注解,导致异步方法失效。

@Configuration
@EnableAsync // 开启异步支持
public class AppConfig {
    // ...
}

2.异步方法必须要被其它类中的方法调用,如果在同一个类中调用,异步方法仍然是同步执行的。

@Service
public class DemoService {
    @Async
    public void asyncMethod() {
        // ...
    }
    
    public void callAsyncMethod() {
        asyncMethod(); // 异步方法不会被异步执行
    }
}

@Service
public class CallerService {
    @Autowired
    private DemoService demoService;
    
    public void callAsyncMethod() {
        demoService.asyncMethod(); // 异步方法会被异步执行
    }
}

3.异步方法必须要在public方法中被调用,如果被同类中的private方法调用,异步方法仍然是同步执行的。

@Service
public class DemoService {
    @Async
    public void asyncMethod() {
        // ...
    }
    
    public void callAsyncMethod() {
        privateMethod(); // 异步方法不会被异步执行
    }
    
    private void privateMethod() {
        asyncMethod(); // 异步方法不会被异步执行
    }
}

4.异步方法必须是非静态方法,如果是静态方法,异步方法仍然是同步执行的。

@Service
public class DemoService {
    @Async
    public static void asyncMethod() {
        // ...
    }
    
    public void callAsyncMethod() {
        asyncMethod(); // 异步方法不会被异步执行
    }
}

5.异步方法必须要有返回值,如果没有返回值,异步方法仍然是同步执行的。

@Service
public class DemoService {
    @Async
    public void asyncMethod() {
        // ...
    }
    
    @Async
    public Future<String> asyncMethodWithResult() {
        // ...
        return new AsyncResult<>("result");
    }
}

@Service
public class CallerService {
    @Autowired
    private DemoService demoService;
    
    public void callAsyncMethod() {
        demoService.asyncMethod(); // 异步方法不会被异步执行
        Future<String> future = demoService.asyncMethodWithResult(); // 异步方法会被异步执行
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值