SpringAop切面编程步骤

1.引入aop的命名空间,并开启注解:

注意⚠️:这里开启aspectj注解的地方要和使用的bean在同一个上下文里,不然会导致注解不生效。




    
    

2.使用@Aspect注解定义切面、切点和通知

package com.xxx.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;


@Aspect
@Component
public class AopTestDemo {

    @Pointcut("execution(* com.xxx.demo.controller.*Controller.*(..))")
    public void controllerMonitor(){}

    @Before("@annotation(org.springframework.web.bind.annotation.RequestMapping) && controllerMonitor()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("beforeMethod" + Arrays.toString(joinPoint.getArgs()));
    }

    @After("@annotation(org.springframework.web.bind.annotation.RequestMapping) && controllerMonitor()")
    public void afterMethod(JoinPoint joinPoint){
        System.out.println("afterMethod" + Arrays.toString(joinPoint.getArgs()));
    }

    @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) && controllerMonitor()")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("aroundMethod before");
        Object obj = proceedingJoinPoint.proceed();
        System.out.println("aroundMethod" + obj.toString());
         return "拦截测试";
    }

}

你可能感兴趣的:(Spring)