AOP操作

1. AOP术语

  1. 连接点:类里面哪些方法可以被增强,这些方法称为连接点

  2. 切入点:实际被真正增强的方法,称为切入点

  3. 通知(增强):实际增强的逻辑部分称为通知(增强)

    • 前置通知
    • 后置通知
    • 环绕通知
    • 异常通知
    • 最终通知
  4. 切面:把通知应用到切入点的过程

2. 注解方式

  1. 被增强类

    @Component
    public class User {
        public void sayHello(){
            System.out.println("hello");
        }
    }
    
  2. 增强代理类

    @Component
    @Aspect
    public class UserProxy {
    
        @After("execution(* com.yang.aop.User.sayHello(..))")
        public void before(){
            System.out.println("world!");
        }
    
    }
    

    @Aspect注解表示这是一个增强代理类

    @After("execution(* com.yang.aop.User.sayHello(..))")表示增强哪一个方法

    image-20210202153332159

  3. 配置文件中扫描代理类

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <context:component-scan base-package="com.yang.aop"/>
        <aop:aspectj-autoproxy/>
    
    </beans>
    
  4. 不同的增强类型

    • @Before
    • @After
    • @Around
    • @AfterReturning
    • @AfterThrowing

补充:

  • @Pointcut注解可以进行相同切入点提取;
  • 有多个增强类对同一个方法进行增强,可以在类上添加@Order(value)注解,value越小优先级越高

3. 配置文件方式

<bean id="user" class="com.yang.aop.User"/>
<bean id="userProxy" class="com.yang.aop.UserProxy"/>

<aop:config>
 <aop:pointcut id="p" expression="execution(* com.yang.aop.User.sayHello(..))"/>
 <aop:aspect ref="userProxy">
     <aop:after method="before" pointcut-ref="p"/>
 </aop:aspect>
</aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值