自定义注解
1:引入切面pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2:创建自定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.TYPE})
public @interface Log {
String message();
String methodName();
}
3:使用切面
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.demo.project.aopAnnotation.annotation.Log)")
public void annotationPointcut() {
}
@Around("annotationPointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//获取request
HttpServletRequest request = attributes.getRequest();
// 获取url请求参数
System.out.println(request.getParameter("params"));
// 获取注解上面的内容
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
Log apiLog= method.getAnnotation(Log.class);
System.out.println("切入方法注解的message:"+apiLog.message());
System.out.println("切入方法注解的methodName:"+apiLog.methodName());
}
// 获取controller方法名
String methodName = joinPoint.getSignature().getName();
return joinPoint.proceed();
}
}
4:使用自定义注解
@RestController
public class AopController {
@Log(message = "进入",methodName = "demoAopAnnotation")
@RequestMapping("aop")
public void demoAopAnnotation(String params){
System.out.println("进入controller");
}
}