AOP基础,AspectJ Maven 项目 前置通知 后置通知,环绕通知,优先级,重用切入点表达式,用idea

需要导入的包

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.9.4</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.4</version>
</dependency>

配置文件

<!--配置自动扫描的包-->
  <context:component-scan base-package="com.li.aop.impl"></context:component-scan>
  <!--使AspjectJ 注解起作用,自动为匹配的类生成代理对象-->
  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

LoggingAsgectj 类是前置通知类

package com.li.aop.impl;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//把这个类声明为一个切面:需要把该类放入到IOC容器中
@Aspect
@Component
public class LoggingAsgectj {
    //声明该方法是一个前置通知,在目标方法开始之前执行
    @Before("execution(public int com.li.aop.impl.AtithmeticCalculatorImpl.add(int,int))")
    public void beforeMethod(){
        System.out.println("before");
    }
}

 在些方法前执行

package com.li.aop.impl;

import org.springframework.stereotype.Component;

@Component
public class AtithmeticCalculatorImpl implements AtithmeticCalculator {
//此方法前执行
    public int add(int i, int j) {

        int result = i +j;

        return result;
    }

    public int sub(int i, int j) {

        int result = i -j;

        return result;
    }

    public int mul(int i, int j) {

        int result = i *j;

        return result;
    }

    public int div(int i, int j) {

        int result = i /j;

        return result;
    }
}

@After 后置通知

@Order 优先级

@Pointcut 重用切入点表达式

package com.li.aop.after;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AfterMethod {

    //定义声名切入点表达式的方法
    @Pointcut("execution(public int com.li.aop.after.AtithmeticCalculatorImpl.*(int,int))")
    public void decelareJoinPointExecution(){
    }
//后置通知
    @After("decelareJoinPointExecution()")
    public void afterMethod(JoinPoint joinPoint){
        System.out.println("after...");
    }
//后置返回通知
    @AfterReturning("decelareJoinPointExecution()")
    public void afterMethodReturn(JoinPoint joinPoint){
        System.out.println("afterReturn...");
    }
//后置异常通知
    @AfterThrowing(value = "decelareJoinPointExecution()",throwing = "ex")
    public void afterMethodThrowing(JoinPoint joinPoint, Exception ex){
        System.out.println("afterThrowing...");
    }
//环绕通知
    @Around("decelareJoinPointExecution()")
    public int aroundMethodReturn(ProceedingJoinPoint proceedingJoinPoint){
        System.out.println("aroundReturn...");
        return 100;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值