AOP基于注解的方式切面编程

<!--开启自动扫描-->
<content:component-scan base-package="com.aop"></content:component-scan>
<!--使Aspject注解起作用,自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

package com.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;
import java.util.List;

//@Component
//@Aspect
public class LoginAspect {
//定义一个方法,声明切入点表达式,该方法里面不需要写代码
// @Pointcut(“execution(* com.aop..(int ,int))”)
// public void JoinPoint(){}
// 前置通知
@Before(“execution(* com.aop..(int ,int))”)
public void beforeMethod(JoinPoint joinPoint) {
String methodName=joinPoint.getSignature().getName();
List list= Arrays.asList(joinPoint.getArgs());
System.out.println(“beforeMethod。。。”+methodName+“with”+list);
}
// //后置通知,是否异常都会执行
// @After(“execution(* com.aop..(int ,int))”)
// public void beforeMethod(JoinPoint joinPoint) {
// String methodName=joinPoint.getSignature().getName();
// List list= Arrays.asList(joinPoint.getArgs());
// System.out.println(“beforeMethod。。。”+methodName+“ends”+list);
// }

// //返回通知,可以获得执行方法的结果
// @AfterReturning(value = “execution(* com.aop..(int ,int))”,returning = “result”)
// public void AfterReturning(JoinPoint joinPoint,Object result) {
// String methodName=joinPoint.getSignature().getName();
// List list= Arrays.asList(joinPoint.getArgs());
// System.out.println(“AfterReturning。。。”+methodName+“ends”+list+“返回值:”+result);
// }

// //异常通知
// @AfterThrowing(value = “execution(* com.aop..(int ,int))”,throwing = “ex”)
// public void AfterThrowing(JoinPoint joinPoint,Exception ex) {
// String methodName=joinPoint.getSignature().getName();
// List list= Arrays.asList(joinPoint.getArgs());
// System.out.println(“AfterReturning。。。”+methodName+“ends”+list+“异常:”+ex);
// }

//环绕通知,必须要有ProceedingJoinPoint类型参数,
//要有返回值,返回值结果就是方法结果

// @Around( “JoinPoint()”)
public Object Around(ProceedingJoinPoint joinPoint) {
Object result=null;
String methodName=joinPoint.getSignature().getName();

    try {
        //前置通知
        System.out.println("前置通知:"+Arrays.asList(joinPoint.getArgs()));
        //执行目标方法
        result=joinPoint.proceed();
        System.out.println("后置通知:"+result);

    } catch (Throwable e) {
        System.out.println("异常通知"+e);
        throw new RuntimeException(e);
    }

    return result;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值