代码
1.先声明一个注解接口类
package com.mycompany.myapp.aop.logging;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
}
2.实现该注解,(已实现参数、返回结果、异常的日志输出,并不影响方法本身异常抛出)
•AspectJ 支持 5 种类型的通知注解:
–@Before: 前置通知, 在方法执行之前执行
–@After: 后置通知, 在方法执行之后执行
–@AfterRunning: 返回通知, 在方法返回结果之后执行
–@AfterThrowing: 异常通知, 在方法抛出异常之后
–@Around: 环绕通知, 围绕着方法执行
package com.mycompany.myapp.aop.logging;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class SysLogAspect {
/**
* 此处的切点是注解的方式,也可以用包名的方式达到相同的效果
*/
@Pointcut("@annotation(com.mycompany.myapp.aop.logging.SysLog)")
public void log() {
}
/**
* 环绕通知,使用在方法log()上注册的切入点
*
* @param joinPoint
* @return
* @throws Throwable
*/
@Around(value = "log()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 返回
Object proceed = joinPoint.proceed();
return proceed;
}
/**
*返回通知: 处理完请求,返回内容
*
* @param ret
*/
@AfterReturning(returning = "ret", pointcut = "log()")
public void doAfterReturning(JoinPoint joinPoint,Object ret) {
System.out.println("方法的返回值 : " + ret);
// 获取执行方法的类的名称(包名加类名)
String className = joinPoint.getTarget().getClass().getName();
Logger log = LogManager.getLogger(className);
// 获取实例和方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 记录日志
log.info(method.getName() + " Returns:" + JSON.toJSONString(ret));
}
/**
* 异常通知 用于拦截记录异常日志
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "log()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
System.out.println("发生异常");
// 获取执行方法的类的名称(包名加类名)
String className = joinPoint.getTarget().getClass().getName();
Logger log = LogManager.getLogger(className);
// 获取实例和方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 记录日志
log.error(method.getName() + " error:{}",e);
}
/**
* 前置通知:进入方法前执行
*
* @param joinPoint
*/
@Before("log()")
public void doBeforeAdvice(JoinPoint joinPoint) {
System.out.println("进入方法前执行.....");
// 获取执行方法的类的名称(包名加类名)
String className = joinPoint.getTarget().getClass().getName();
Logger log = LogManager.getLogger(className);
// 获取实例和方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 记录日志
Object[] args = joinPoint.getArgs();
// log.info(method.getName() + " Params:" + JSON.toJSONString(args));
log.info(method.getName() + " Params:" + Arrays.toString(args));
}
/**
* 后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
*/
@After("log()")
public void after(JoinPoint joinPoint) {
System.out.println("方法最后执行.....");
}
使用
直接在想要使用日志的方法加注解
已生效