注解,写一个简单的注解,用于标记方法;标记的方法当aop的切点
/**
* 自定义注解:日志记录
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAop {
}
方法应用
@RestController
@RequestMapping("/xxx")
public class XxxController {
@Autowired
private UserService userService;
//注解标记
@LogAop
@GetMapping("/getOrder/{id}")
public String getOrder(String id) {
String data = userService.getInfo(a);
return data;
}
}
AOP方法
@Aspect
@Component
public class HttpLog {
@Autowired
private XxxxDao xxxxDao;
/**
* 1.设置切点
*/
@Pointcut("@annotation(com.xxx.start.server.xxx.LogAop)")
private void pointCut() {
}
@Around("pointCut()")
public Object httpLog(ProceedingJoinPoint joinPoint) {
long millisStart = System.currentTimeMillis();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object proceed = "请求异常";
//方法
String method = request.getMethod();
//对象
String name = joinPoint.getTarget().getClass().getName();
//参数
Object[] args = joinPoint.getArgs();
System.out.println(args.toString());
StringBuffer stringBuffer = new StringBuffer();
//参数拼接
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (i == args.length - 1 && arg != null) {
stringBuffer.append(arg.toString());
} else if (arg != null) {
stringBuffer.append(arg.toString()).append(",");
}
}
try {
proceed = joinPoint.proceed();
long end = System.currentTimeMillis();
long resultTime = end - millisStart;
//proceed 是返回数据,around 的专用,会有两次,当时间不同时,才是第二次
if (resultTime != 0) {
System.err.println("请求参数:" + stringBuffer);
//查询sql
List<xxx> data = xxxxDao.selectData();
System.err.println("aop sql---->" + all);
}
return proceed;
} catch (Throwable throwable) {
System.out.println("err:" + throwable);
return proceed + throwable.toString();
}
}
}