1. 程式人生 > >SpringBoot AOP示例

SpringBoot AOP示例

execution ann 運算 作用 static 子類 turn leg ram

AOP主要註解:

@Aspect,作用在類上,說明這是一個Aspect切面類。
@Pointcut,用來描述,你需要在哪些類的哪些方法中植入你的代碼。
@Adive,與Pointcut配合使用,主要說明在Pointcut標記方法的什麽時機執行,執行之前?執行之後?

@Pointcut express(切面表達式)

designators指示器:
匹配方法:execution() 通過什麽方式去匹配哪些類的哪些方法(重點掌握)。
匹配註解:@annotation() @args() @within() @target()
匹配包/類型:within()
匹配對象:this() bean() target()
匹配參數:args()

wildcards通配符:

 *  匹配任意數量的字符
 ..  匹配指定類及其子類
 +  匹配任意數的子包或參數

operators運算符:&&與 ||或 !非

5中Advice

@Before
@After
@AfterReturning
@AfterThrowing
@Around

示例代碼

@Aspect
@Component
public class HttpAspect {
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.imooc.controller.GirlController.*(..))")
    public void log(){
    }

    /**
     * 在截取的方法前執行
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // url
        logger.info("url={}", request.getRequestURL());
        // method
        logger.info("method={}", request.getMethod());
        // ip
        logger.info("ip={}", request.getRemoteAddr());
        // 類方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // 參數
        logger.info("args={}", joinPoint.getArgs());
    }

    /**
     * 獲取方法返回參數
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}", object);
    }
}

Advice示例

@Aspect
@Component
public class AdviceAspectConfig {

    /********PointCut********/

    @Pointcut("@annotation(com.vmware.AopExecutionDemo.annotation.AdminOnlyMethod)")
    public void matchAnnotation(){}

    @Pointcut("execution(* com.vmware.AopExecutionDemo.service.*.find*(int))")
    public void matchIntArgs(){}

    @Pointcut("execution(public * com.vmware.AopExecutionDemo.service..*.*(..) throws java.lang.IllegalAccessException)")
    public void matchExecption(){}

    @Pointcut("execution(int com.vmware.AopExecutionDemo.service.*.*(..))")
    public void matchReturn(){}

    /********Advice********/

    /**
     * 獲取方法輸入的參數
     * @param productId
     */
    @Before("matchIntArgs() && args(productId)")
    public void before(int productId){
        System.out.println("### before ### productId = [" + productId + "]");
    }

    /**
     *  獲取方法返回參數
     * @param result
     */
    @AfterReturning(value = "matchReturn()", returning = "result")
    public void after(int result){
        System.out.println("### after ###:" + result);
    }

    /**
     * Before + After + AfterReturning
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("matchReturn()")
    public Object after(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("### before ###");
        Object result;
        result = joinPoint.proceed(joinPoint.getArgs());
        System.out.println("### after ###" + result);
        return result;
    }   
}

@annotation示例

@Aspect
@Component
public class AnnotationAspectConfig {

    /**
     * 匹配帶有 AdminOnlyMethod Annotation的方法
     */
    @Pointcut("@annotation(com.vmware.AopExecutionDemo.annotation.AdminOnlyMethod)")
    public void matchAnnotation(){}

    @Before("matchAnnotation()")
    public void before(){
        System.out.println("###matchAnnotation && Before");
    }
}
@Aspect
@Component
public class AnnotationClassAspectConfig {

    /**
     * 匹配帶有 AdminOnlyClass Annotation的類
     */
    @Pointcut("@within(com.vmware.AopExecutionDemo.annotation.AdminOnlyClass)")
    public void annotationClassCondition(){}


    @Before("annotationClassCondition()")
    public void before(){
        System.out.println("###annotationClass && before");
    }
}

SpringBoot AOP示例