Spring AOP(面向切面) 注解使用方法

开启自动织入支持

在XML中开启

添aop标签

   <aop:aspectj-autoproxy />

开启注解支持,同时强制指定代理机制为cglib

<aop:aspectj-autoproxy proxy-target-class="true" />

通过注解开启

@Configuration
// 开启注解支持,同时强制指定代理机制为cglib
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyAOPConf {}
@Component
@Aspect //表示这是一个切面类,里面的方法都是像打印日志等围绕业务方法的方法

注解方式入口类

@Configuration                //相当生成一个XML文件
@ComponentScan(basePackages = "com.lanou3g.spring.simple.say")//扫描路径
@EnableAspectJAutoProxy         //开启对AOP相关注解的处理
public class AppByAnnotation {
...
}

注解方式定义切面类

@Pointcut:切入点的注解
由于@Aspect注解没有让Spring作为组件bean扫描的能力,所以我们需要额外添加@Component注解

@Aspect     // 表示该类是一个切面
@Component  // Aspect切面首先必须也是一个普通的bean
public class MethodInOutAspect {
}
Spring的注解的AOP的通知类型
环绕通知@Around

指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式

    @Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
    public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {}
    // 获取连接点方法的名称
    String methodName = joinPoint.getSignature().getName();

    // 获取连接点方法的参数
    Object[] args = joinPoint.getArgs();
@Before:前置通知
 @Before("com.lanou3g.spring.GlobalPointcut.say_all_method()")
@AfterReturning:后置通知
@AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
@AfterThrowing:异常抛出通知
   @AfterThrowing(value="execution(* "com.lanou3g.spring.GlobalPointcut.say_all_method()" , throwing="e")
@After:最终通知
   @After("com.lanou3g.spring.GlobalPointcut.say_all_method()")

方法名功能
Signature getSignature();获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息
Object[] getArgs();获取传入目标方法的参数对象
Object getTarget();获取被代理的对象
Object getThis();获取代理对象
Object proceed() throws Throwable执行目标方法
Object proceed(Object[] var1) throws Throwable传入的新的参数去执行目标方法

通过@Pointcut注解定义切入点表达式

拦截com.lanou3g.spring.simple.say包下所有类(包括子包中所有类)中的所有方法
@Pointcut(“execution(* com.lanou3g.spring.simple.say….(…))”)
public void say_all_method() {}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值