先导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
写AOP配置类
在方法上配置织入方法的织入点
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.SimpleDateFormat;
import java.util.Date;
@Aspect
@Component
public class MyAspect {
@AfterReturning(pointcut = "execution(* com.atguigu.ssyx..*(..))", returning = "result")
public void afterMethodExecution(JoinPoint joinPoint, Object result) {
System.out.println("");
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
String className = joinPoint.getTarget().getClass().getName();
System.out.println("=========================="+"方法名称:"+ className + "." + methodName +"==============================" );
System.out.println("参数列表:");
if (arguments != null && arguments.length > 0) {
Signature signature = joinPoint.getSignature();
Method method = getMethod(signature);
if (method != null) {
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
System.out.print(parameters[i].getName() + ":" + getArgumentValue(arguments[i]) + ",");
}
}
} else {
System.out.print("无");
}
System.out.println(" ");
System.out.println(" ");
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.print("返回值:\n" + objectMapper.writeValueAsString(result));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("");
System.out.println("===================================="+printTime()+"=============================");
}
private Method getMethod(Signature signature) {
if (signature instanceof MethodSignature) {
MethodSignature methodSignature = (MethodSignature) signature;
return methodSignature.getMethod();
}
return null;
}
private String getArgumentValue(Object argument) {
if (argument != null) {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper.writeValueAsString(argument);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return "null";
}
private String printTime(){
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
return("当前方法执行时间: " + formattedDate);
}
}