自定义注解在AOP中的应用

以下介绍面向切面编程的两种主要方式:


一、使用execution定义pointcut方式

1、定义切面
@Aspect
@Component
public class LogIntercept {

//  com.example.demo包下任意公共的(public)方法————解析切入点:public表示操作方法的权限,第一个*表示返回值,com.glodon.action表示报名,..表示子包,第二个*表示类,第三个*表示方法名称,(..)表示参数
    @Pointcut(value="execution(public * com.example.demo..*.*(..))")
    public void writeLog() {
    }
//    前置拦截,在执行目标方法之前的操作
    @Before("writeLog()")
    public void before() {
        this.printLog("@Before 方法执行前——————做日志");
    }
//   环绕拦截,在执行目标方法的前后的操作
    @Around("writeLog()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        this.printLog("@Around 方法执行前——————做日志");
        pjp.proceed();
        this.printLog("@Around 方法执行后——————做日志");
    }
//      后置拦截,在执行目标方法之前的操作
    @After("writeLog()")
    public void after() {
        this.printLog("@After 方法执行后——————做日志");
    }

    private void printLog(String str) {
        System.out.println(str);
    }
}
2、使用切面
@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        return "hello";
    }
}

二、使用注解定义pointcut方式

1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AroundTest {
    String name() default "测试";
}
2、定义切面
@Component
@Aspect
public class AroundTestInteceptor {
    public AroundTestInteceptor(){
    }

  /**
   * 定义切入点
   */
  @Pointcut(value="@annotation(com.example.demo.AroundTest)")
    public void logAnnotatedMethod() {
    }

    /**
     * 拦截方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("logAnnotatedMethod()")
    public void inteceptorAction(ProceedingJoinPoint pjp) throws Throwable {
        Object o = null;
        MethodSignature joinPointObject = (MethodSignature) pjp.getSignature(); 
        Method method = joinPointObject.getMethod();   
        AroundTest annotation = method.getAnnotation(AroundTest.class); 
        Date enterDate = new Date();
        System.out.println("开始执行方法:" + annotation.name());
        //用于执行委托对象的目标方法
        o = pjp.proceed();
        Date leaveDate = new Date();
        System.out.println("结束执行方法:"+ annotation.name() +",方法执行的时间:" + (leaveDate.getTime() - enterDate.getTime()));
    }
}
3、使用切面
@Component
public class PowerBoot implements ApplicationRunner {
    private int i = 0;
    @Override
    @AroundTest
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("自启动开启");
    }
}

参考:
http://www.imooc.com/article/2670

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值