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