一、自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CopyAsync {
}
二、编写AOP切面类
@Aspect
@Component
public class CopyAsyncAop {
@Around(value = "@annotation(com.xx.CopyAsync)")
public void around(ProceedingJoinPoint joinPoint) {
try {
// 一般使用线程池
new Thread(() -> {
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}, "线程xx").start();
} catch (Throwable throwable) {
}
}
}
三、调用测试类
@RestController
@Slf4j
public class Test {
@Autowired
private TestService testService;
@RequestMapping("/add")
public String add() {
log.info("1");
testService.asyncLog();
log.info("3");
return "3";
}
}
四、TestService类
@Component
@Slf4j
public class TestService {
@CopyAsync
public void asyncLog() {
try {
log.info("目标方法开始执行,阻塞10秒");
Thread.sleep(10000);
log.info("2");
} catch (Exception e) {
}
}
}