AOP

AOP

maven依赖

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-aop</artifactId>  
</dependency> 

 自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Time {
}

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

/**
 * @author zfang
 * @date 2020/7/10
 */

@Aspect
@Component
public class WebAspect {
    //private static final String E = "execution(* com....ProjectTypeController.*(..))";
    private static final String E = "@annotation(com....Time)";

    /**
     * 切入点
     */
    @Pointcut(E)
    public void executePackage() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before("executePackage()")
    public void before(JoinPoint joinPoint) {
        System.out.println("前置通知");
    }

    /**
     * 后置最终通知
     */
    @After("executePackage()")
    public void after() {
        System.out.println("后置最终通知");
    }

    /**
     * 后置返回通知
     *
     * @param joinPoint
     * @param keys
     */
    @AfterReturning(value = E, returning = "result")
    public void afterReturning(JoinPoint joinPoint, String result) {
        System.out.println("后置返回通知");
        System.out.println("后置返回通知 返回值:" + result);
    }

    @Around(E)
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - start;
        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return result;
    }

    /**
     * 后置异常通知
     *
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(value = "executePackage()", throwing = "tw")
    public void exp(Throwable tw) {
        System.out.println("后置异常通知");
        System.out.println(tw.getMessage());
    }
}

 

 

posted on 2020-07-10 10:01  1zfang1  阅读(147)  评论(0编辑  收藏  举报

导航