spring aop操作 (基于AspectJ注解方式)

aop操作(基于AspectJ注解方式)

  1. 创建一个类 在类中定义方法,实现对类的方法增强

  2. 创建一个增强类,编写增强的逻辑

    1. 在增强类中创建方法 让不同的方法代表不同的通知类型
  3. 进行通知的配置

    1. 在spring配置文件中 开启注释

      <?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 http://www.springframework.org/schema/beans/spring-beans.xsd
                                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                                 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
      
      <!--    开启注解的扫描-->
          <context:component-scan base-package="com.zh"></context:component-scan>
      
    2. 使用注解创建user和userproxy两个对象

      //被增强的类
      @Component
      public class User {
          public void add(){
              System.out.println("add.............");
          }
      }
      //增强的类
      @Component
      @Aspect//生成代理对象
      public class UserProxy {
          //前置通知
          public void before(){
              System.out.println("before.........");
      
          }
      }
      
    3. 在增强的类上添加一个注解 @aspect

      //增强的类
      @Component
      @Aspect//生成代理对象
      public class UserProxy {
          //前置通知
          public void before(){
              System.out.println("before.........");
      
          }
      }
      
    4. 在spring配置文件中 开启生成代理对象`

      <!--    开启aspectJ生成代理对象-->
          <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
      </beans>
      
    5. 配置不同类型的通知

      1. 在我们增强类的里边 在作为通知方法上面 添加通知类型注解 使用切入点表达式配置

        //前置通知
        //before 注解表示作为前置通知
        @Before(value = "execution(* com.zh.demo2.User.add())")
        public void before(){
            System.out.println("before.........");
        }
        
        //环绕通知 在add之间 和之后都执行
        @Around(value = "execution(* com.zh.demo2.User.add())")
        public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("环绕之前");
            //执行被增强的方法
            proceedingJoinPoint.proceed();
            System.out.println("环绕之后");
        }
        
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值