切点类必须加入@Aspect注解(切面)
通知指的就是指拦截到连接点之后要执行的代码,通知分为
前置@before 、后置@after、异常@afterThrowing、最终@afterReturning、环绕@around通知五类,返回的值是切点处的方法名
实际例子:
package com.example.demo.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
@Component
@Aspect //切面
public class LoginAOP {
@Autowired
private StringRedisTemplate srt;
@Pointcut("execution(* com.example.demo.ceshi..*.*(..))")
public void logPointCut() {
}
@Around("logPointCut()") //环绕
public Object around(ProceedingJoinPoint joinPoint) throws Throwable { //ProceedingJoinPoint joinPoint传过来的可以是任何东西
Object[] args = joinPoint.getArgs();
System.out.println(joinPoint.getSignature().getName());
String methodName=joinPoint.getSignature().getName(); //打印的是getSignature()传过来的是方法名
if("tologin".equals(methodName) || "dologin".equals(methodName)) { //如果传过来的参数等于"tologin"或者"dologin"正常运行到登录页面
return joinPoint.proceed();
}
for (int i = 0; i < args.length; i++) {
System.out.println("第" + (i+1) + "个参数为:" + args[i]);
}
if (srt.opsForValue().get(args[1]) == null) {
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
return mv;
}
return joinPoint.proceed();
}
}