1.引入aop 需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.创建controller切面对象
@Aspect
@Component
@Order(4)
public class InfoAspect {
@Pointcut("execution(public * com.sf.controller.WhController.whPage*(..))")
public void executeService() {
System.out.println("进入executeService");
}
@Before("executeService()")
public void exBefore(JoinPoint pjp){
System.out.println("executeService Before");
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
long startTime = System.currentTimeMillis();
request.setAttribute("startTime",startTime);
}
// 通知
@Around("executeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("executeService Around");
// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
try {
}catch (Exception e){
e.printStackTrace();
}
return result;
}
// 执行切点之后
@After("executeService()")
public void exAfter(JoinPoint joinPoint) {
System.out.println("excuteService After");
}
}
3.创建切面service对象
新建切面对象,上端代码中的表达式改为 execution(* com.sf.*.*Service.get*(..))