SpringBoot中使用AOP备忘
1. pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 示例代码
@Aspect
@Component
public class HttpAspect {
private static final Logger logger=LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.springboot.controller.GirlController.*(..))")
public void log(){
}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=requestAttributes.getRequest();
logger.info("url={}",request.getRequestURL());
logger.info("method={}",request.getMethod());
logger.info("ip={}",request.getLocalAddr());
logger.info("class_method={}",joinPoint.getSignature().getDeclaringType()+"."+joinPoint.getSignature().getName());
logger.info("args={}",joinPoint.getArgs());
}
@After("log()")
public void doAfter(){
logger.info("doAfter={}",2222222);
}
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
logger.info("response={}",object.toString());
}
}
3. 自定义注解 + AOP配置 + 切面类内部获取请求参数方法名等
3-1 创建一个注解类
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CDS {
String value() default "primary";
}
3-2 创建一个切面类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
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.util.Arrays;
import java.util.List;
@Component
@Aspect
public class CAspect {
@Before("@annotation(cn.test.CDS))")
public void befor(JoinPoint joinPoint){
Object targetObj =joinPoint.getTarget();
System.out.println(targetObj.getClass().getName());
String methodName = joinPoint.getSignature().getName();
System.out.println("切入方法名字:"+methodName);
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
CDS2 apiLog= method.getAnnotation(CDS2.class);
System.out.println("切入方法注解的title:"+apiLog.value());
}
Object[] args = joinPoint.getArgs();
String[] parameterNames = methodSignature.getParameterNames();
Class[] parameterTypes = methodSignature.getParameterTypes();
for(Object o :args){
System.out.println("切入方法的参数:"+o);
}
}
}
3-3 自定义注解的使用
@GetMapping("/info")
@CDS
public void info( String userId){
System.out.println("测试方法~~~~");
}