AspectJ框架实现AOP

使用注解配置

  1. 配置IOC容器扫描包
  2. 配置AspectJ
    <aop:aspectj-autoproxy />
  3. 编写类和切面方法
    1. 类名上添加注解
      @Compoent@Aspect
    2. 方法名上添加注解
      • 一共有五种注解:
        @Before:前置通知,方法执行前
        @After:后置通知,方法执行后,即使方法抛出异常也会执行,但是还不能访问方法返回的结果。
        @AfterReturning:返回通知,在方法返回结果之后执行,抛异常则不执行
        @AfterThrowing:异常通知,抛出异常后。可通过throwing属性来指定异常的名字。
        @Around:环绕通知。修饰的方法必须携带ProceedingJoinPoint参数,并且要有返回值。通过调用ProceedingJoinPoint的proceed()方法就来决定目标方法的执行。
        ex:@Before("execution(public int per.yrj.Calculator.add(int, int))")括号里面是指定目标方法。
      • JoinPoint参数:当需要获取目标方法的一些信息时可在方法中添加一个形参(如果不需要可以不加)。
      • Exception参数:当需要获取目标方法的一些信息时可在方法中添加一个形参(如果不需要可以不加,只能使用在异常通知的方法上)。
  4. 在切面方法的注解中添加切面表达式来指定方法的作用范围
    ex:"execution(public int per.yrj.Calculator.*(..))"
    格式为: 修饰符+返回值+类的全路径.方法名(参数列表)

    使用@order修饰类指定切面优先级,值越小,优先级越高。
    使用@Pointcut来重用切面表达式:

    1. 定义一个空方法,并用@Pointcut来修饰。
    2. 以后其他需要用到切面表达式的都可以通过该空方法来代替。
      ex:
      @Product("execution(public int per.yrj.Calculator.*(..))")
      public void declareJoinPointExpression(){}
      
      @Before("declareJoinPointExpression()")
      public void beforeMethod(){
          ...
      }

使用xml配置

1.配置IOC容器扫描包
2.编写一个类

@Component
public class CalculatorAspect {
    // 方法名可随意指定
    public void beforeMethod(){
        System.out.println("before...");
    }

    public void afterMethod(){
        System.out.println("after...");
    }

}

3.配置AspectJ

<!-- 切面类 -->
    <bean id="calculatorAspect2" class="per.yrj.xml.CalculatorAspect"/>

    <aop:config>
        <!--配置切点表达式-->
        <aop:pointcut id="pointcut" expression="execution(* per.yrj.xml.impl.CalculatorImpl.*(..))"/>
        <!-- 配置切面类 -->
        <aop:aspect ref="calculatorAspect2">
            <!--配置类中的方法,引用切点表达式-->
            <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
            <aop:after method="afterMethod" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值