AspectJ的注解配置

@Aspect注解是不能够通过类路径自动检测发现的,所以需要配合@Component注释或者在xml配置bean

一个类中的@Aspect注解标识它为一个切面,并且将自己从自动代理中排除(原因:不能陷入死循环)

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

    String value();

}


@Service
public class MoocBiz {

    @MoocMethod("MoocBiz save with MoocMethod.")
    public String save(String arg) {
        System.out.println("MoocBiz save : " + arg);
//      throw new RuntimeException(" Save failed!");
        return " Save success!";
    }

}

@Component
@Aspect
public class MoocAspect {
    //指定切点
    @Pointcut("execution(* com.imooc.aop.aspectj.biz.*Biz.*(..))")
    public void pointcut() {}
    //winin:一个范围
    @Pointcut("within(com.imooc.aop.aspectj.biz.*)")
    public void bizPointcut() {}

    @Before("pointcut()")
    public void before() {
        System.out.println("Before.");
    }
    pointcut()为存在@Pointcut的方法名,args(arg)传入参数属性名为arg,可以获得传入切点的参数内容,也可通过@annotation获得切点的注解内容
    @Before("pointcut() && args(arg)")
    public void beforeWithParam(String arg) {
        System.out.println("BeforeWithParam." + arg);
    }

    @Before("pointcut() && @annotation(moocMethod)")
    public void beforeWithAnnotaion(MoocMethod moocMethod) {
        System.out.println("BeforeWithAnnotation." + moocMethod.value());
    }
    //可以获得切点的返回值
    @AfterReturning(pointcut="bizPointcut()", returning="returnValue")
    public void afterReturning(Object returnValue) {
        System.out.println("AfterReturning : " + returnValue);
    }
    //可以获得切点抛出的异常信息
    @AfterThrowing(pointcut="pointcut()", throwing="e")
    public void afterThrowing(RuntimeException e) {
        System.out.println("AfterThrowing : " + e.getMessage());
    }

    @After("pointcut()")
    public void after() {
        System.out.println("After.");
    }
//around 第一个参数必须为ProceedingJoinPoint
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Around 1.");
        Object obj = pjp.proceed();
        System.out.println("Around 2.");
        System.out.println("Around : " + obj);
        return obj;
    }

}
Around 1.
Before.
BeforeWithAnnotation.MoocBiz save with MoocMethod.
BeforeWithParam.This is test.
MoocBiz save : This is test.
Around 2.
Around :  Save success!
After.
AfterReturning :  Save success!
  <context:component-scan base-package="com.imooc.aop.aspectj"/>
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值