springboot中@Async是否会出现类似事务注解不生效问题

springboot中@Async是否会出现类似事务注解不生效问题

事务注解不生效一般和调用有关,例如:如下情况,使用this调用本地加了事务注解的方法,这种情况事务是无效的

@Service
class A {
    public void testB() {
        this.testC();
    }
    @Transactional
    public void testC() {

    }
}

那么问题来了,@Async注解是否也会出现注解不生效?

测试代码如下:

@Controller
@RequestMapping("/test")
public class Testpush {
    @Autowired
    private AsynService asynService;

    @Autowired
    private ApplicationContext appContext;

    @PostMapping("/asyn")
    @ResponseBody
    public String testAsyn(@RequestBody String a) {

        System.out.println(Thread.currentThread().getName());
        System.out.println();

        long start = System.currentTimeMillis();
        asynService.testAsyn();
        System.out.println("耗时:" + (System.currentTimeMillis() - start));
        return "成功!";
    }
}

@Service
interface AsynService {
    void testAsyn();

    void syn();
}

@Service
class AsynServiceImpl implements AsynService {
    @Override
    public void testAsyn() {
        this.syn();
    }

    @Async
    public void syn() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

最后调用输出结果为:

http-nio-21002-exec-2

耗时:5001

最终结论为:采用this调用加@Async注解的方法,@Async会生效!

注意:当使用注入的方式调用自己方法时,可以采用如下方式。

AsynService bean = appContext.getBean(AsynService.class);
bean.syn()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值