Spring-AOP注解实现

AOP注解方式

首先在入口类中开启注解、开启扫描路径,然后开启对AOP相关注解的相关处理:

@Configuration
@ComponentScan(basePackages = "com.lanou3g.spring.simple.say")
@EnableAspectJAutoProxy //开启对AOP相关注解的处理
public class AppByAnnotation {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppByAnnotation.class);
        ISayHello hello = ctx.getBean(ISayHello.class);
        hello.sayHello("JinSaiSai");
    }
}

写一个需要切入的类:

@Component
public class SayHelloImpl implements ISayHello {

    @Override
    public void sayHello() {
      log.info("hello world!");
    }

    @Override
    public void sayHello(String name) {
        log.info("hello, " + name);
    }
}

单独定义一个类用一个方法定义系统中所有用到的切入点表达式:

public class GlobalPointcut {

    /**
     * 通过@Pointcut注解定义切入点表达式
     * 此处表达式含义:拦截com.lanou3g.spring.simple.say包下所有类(包括子包中所有类)中的所有方法
     */
    @Pointcut("execution(* com.lanou3g.spring.simple.say..*.*(..))")
    public void say_all_method() {}

}

定义一个切面,负责收集方法调用的入参、出参(返回值):

public class MethodInOutAspect {

    // 指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式
    @Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
    public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取连接点方法的名称
        String methodName = joinPoint.getSignature().getName();

        // 获取连接点方法的参数
        Object[] args = joinPoint.getArgs();

        log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 开始执行");
        Object retuVal = joinPoint.proceed();
        log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 返回值: " + retuVal);
        return retuVal;
    }

    @AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
    public Object afterRM(Object ret) {
        log.debug("[afterRM] 返回值: " + ret);
        return ret;
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值