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()