Spring-AOP

Spring-AOP


一、AOP简介

AOP = Aspect Oriented Programming 面向切面编程,是一种编程范式,与 Object Oriented Programming(OOP 面相对象编程) 相同

AOP是Spring 继Ioc容器第二个重要概念,Spring的特征就是Ioc容器和Aop编程。

AOP与代理模式相同,利用代理实现对目标对象在不修改源码的情况下进行功能增强等操作,但是Spring理念无入侵/无侵入,用户感知不到。且在开发过程中,代码更加简洁,作用范围更广。

AOP应用场景:

​ 1、对目标方法进行耗时统计

​ 2、对目标添加事务管理

​ 3、对目标添加权限访问等。。。

二、 AOP核心概念
  • 连接点(JoinPoint):正在执行的方法,例如:update()、delete()、select()等都是连接点。
  • 切入点(Pointcut):匹配连接点的式子
    • 在SpringAOP中,一个切入点可以只描述一个具体方法,也可以匹配多个方法
      • 一个具体方法:top.newhand.dao包下的BookDao接口中的无形参无返回值的save方法
      • 匹配多个方法:所有的save方法,所有的get开头的方法,所有以Dao结尾的接口中的任意方法,所有带有一个参数的方法
  • 通知(Advice):在切入点前后执行的操作,也就是增强的共性功能
    • 在SpringAOP中,功能最终以方法的形式呈现
  • 通知类:通知方法所在的类叫做通知类
  • 切面(Aspect):描述通知与切入点的对应关系,也就是哪些通知方法对应哪些切入点方法。
  • 目标对象(Target):被代理的对象,也叫原始对象,该对象中的方法没有任何功能增强。
    代理对象(Proxy):代理后生成的对象,由Spring帮我们创建代理对象。
三、AOP工作流程

​ 1、Spring容器启动

​ 2、读取所有切面配置中的切入点

​ 3、初始化bean, 判定bean对应的类中的方法是否匹配到任意切入点

​ 匹配失败,创建原始对象

​ 匹配成功,创建原始对象(目标对象)的代理对象

​ 4、获取bean执行方法

​ 获取的bean是原始对象时,调用方法并执行,完成操作

​ 获取的bean是代理对象时,根据代理对象的运行模式运行原始方法与增强的内容,完成操作

四、AOP切入点表达式
  • 切入点:要进行增强的方法

  • 切入点表达式:要进行增强的方法的描述方式

    • 描述方式一:执行top.newhand.dao包下的BookDao接口中的无参数update方法
    execution(void top.newhand.dao.BookDao.update())
    
    • 描述方式二:执行top.newhand.dao.impl包下的BookDaoImpl类中的无参数update方法
    execution(void top.newhand.dao.impl.BookDaoImpl.update())
    
  • 切入点表达式标准格式:动作关键字(访问修饰符 返回值 包名.类/接口名.方法名(参数) 异常名)

    execution(public User top.newhand.service.UserService.findById(int))
    
    • 动作关键字:描述切入点的行为动作,例如execution表示执行到指定切入点
    • 访问修饰符:public,private等,可以省略
    • 返回值:写返回值类型
    • 包名:多级包使用点连接
    • 类/接口名:
    • 方法名:
    • 参数:直接写参数的类型,多个类型用逗号隔开
    • 异常名:方法定义中抛出指定异常,可以省略
  • 通配符

    目的:可以使用通配符描述切入点,快速描述。

    • *:单个独立的任意符号,可以独立出现,也可以作为前缀或者后缀的匹配符出现

    匹配top.newhand包下的任意包中的UserService类或接口中所有find开头的带有一个参数的方法

    execution(public * top.newhand.*.UserService.find*(*))
    
    • … :多个连续的任意符号,可以独立出现,常用于简化包名与参数的书写

    匹配com包下的任意包中的UserService类或接口中所有名称为findById的方法

    execution(public User com..UserService.findById(..))
    
    • +:专用于匹配子类类型
    execution(* *..*Service+.*(..))
    

    书写技巧

    • 所有代码按照标准规范开发,否则以下技巧全部失效
    • 描述切入点通**常描述接口**,而不描述实现类
    • 访问控制修饰符针对接口开发均采用public描述(可省略访问控制修饰符描述
    • 返回值类型对于增删改类使用精准类型加速匹配,对于查询类使用*通配快速描述
    • 包名书写尽量不使用…匹配,效率过低,常用*做单个包描述匹配,或精准匹配
    • 接口名/类名书写名称与模块相关的采用*匹配,例如UserService书写成*Service,绑定业务层接口名
    • 方法名书写以动词进行精准匹配,名词采用匹配,例如getById书写成getBy,selectAll书写成selectAll
    • 参数规则较为复杂,根据业务方法灵活调整
    • 通常**不使用异常作为匹配**规则
    五、AOP通知类型
    • AOP通知描述了抽取的共性功能,根据共性功能抽取的位置不同,最终运行代码时要将其加入到合理的位置
    • AOP通知共分为5种类型
      • 前置通知:在切入点方法执行之前执行
      • 后置通知:在切入点方法执行之后执行,无论切入点方法内部是否出现异常,后置通知都会执行。
      • **环绕通知(重点):**手动调用切入点方法并对其进行增强的通知方式。
      • 返回后通知(了解):在切入点方法执行之后执行,如果切入点方法内部出现异常将不会执行。
      • 抛出异常后通知(了解):在切入点方法执行之后执行,只有当切入点方法内部出现异常之后才执行。
    @Component
    @Aspect
    public class DaoAdvice {
        @Pointcut("execution(void top.newhand.dao.UserDao.save())")
        private void pt() {}
        //前置通知 -- 代理方法执行前执行
        @Before("pt()")
        public void before() {
            System.out.println("UserDao save Before");
        }
        //后置通知 -- 代理方法执行完毕后执行
        @After("pt()")
        public void after() {
            System.out.println("UserDao save After");
        }
        // 环绕通知 -- 自定义代理方法执行顺序
        // ProceedingJoinPoint 是环绕通知必须得参数不可省略 
        @Around("pt()")
        public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("UserDao Around Before");
            // 执行代理方法,如果没有-代理方法就无法执行
            proceedingJoinPoint.proceed();
            System.out.println("UserDao Around After");
            // 当被代理的方法有返回值时,必须要返回值,如果没有可以返回Object也可以设置void
            return new Object();
        }
        // 返回后通知 -- 代理方法执行后通知
        @AfterReturning("pt()")
        public void afterReturning() {
            System.out.println("UserDao AfterReturning");
        }
        // 抛出异常后通知 -- 代理方法执行异常后通知
        @AfterThrowing("pt()")
        public void afterThrowing() {
            System.out.println("UserDao AfterThrowing");
        }
    }
    
    

    下面是这个五种通知的执行顺序,这里没有异常后通知,是因为方法没有抛出异常。
    请添加图片描述

六、AOP切入点数据获取
  • 获取参数

说明:在前置通知和环绕通知中都可以获取到连接点方法的参数们

// 前置通知
@Before("pt()")
public void before(JoinPoint joinPoint) {
    //获取连接点方法的参数们
    Object[] args = joinPoint.getArgs(); 
    System.out.println(Arrays.toString(args));
}
// 环绕通知获取 -- ProceedingJoinPoint是JoinPoint的子类
@Around("pt()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    //获取连接点方法的参数们
    Object[] args = proceedingJoinPoint.getArgs(); 
    System.out.println(Arrays.toString(args));
    Object ret = pjp.proceed();
    return ret;
}
  • 获取返回值

说明:在返回后通知和环绕通知中都可以获取到连接点方法的返回值

// 返回后通知
@AfterReturning(value = "pt()",returning = "ret")
public void afterReturning(String ret) {
    //变量名要和returning="ret"的属性值一致
    System.out.println("afterReturning advice ..."+ret);
}
// 环绕通知
@Around("pt()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // 手动调用连接点方法,返回值就是连接点方法的返回值
    Object ret = pjp.proceed();
    return ret;
}
  • 获取异常

说明:在抛出异常后通知和环绕通知中都可以获取到连接点方法中出现的异常

// 异常后通知
@AfterThrowing(value = "pt()",throwing = "t")
public void afterThrowing(Throwable t) {
    //变量名要和throwing = "t"的属性值一致
    System.out.println("afterThrowing advice ..."+ t);
}
// 环绕通知
@Around("pt()")
public Object around(ProceedingJoinPoint proceedingJoinPoint)  {
    Object ret = null;
    //此处需要try...catch处理,catch中捕获到的异常就是连接点方法中抛出的异常
    try {
        ret = proceedingJoinPoint.proceed();
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return ret;
}
七、AOP 案例
1、AOP入门案例

​ (1)Spring配置类

@Configuration
@ComponentScan("top.newhand")
// 开启AOP自动代理,如果没有默认关闭AOP
@EnableAspectJAutoProxy
public class SpringConfig {
}

​ (2)编写业务

// 这里正常编写业务即可,无需其他特殊配置
public interface UserDao {
    void save();
}
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("book dao Save ...");
    }
}

​ (3)定义通知类,制作通知方法

// AOP通知类必须放入Ioc容器,所以一定要@Component 交由SPring管理
@Component
// @Aspect 定义通知类,如果没有不生效
@Aspect
public class DaoAdvice {
	// 定义切点位置,可以使用通配符, 定义切点方法pt()
    @Pointcut("execution(void top.newhand.dao.UserDao.save())")
    private void pt() {}
	// 制作通知方法,有五种
    //前置通知 -- 代理方法执行前执行
    @Before("pt()")
    public void before() {
        System.out.println("UserDao save Before");
    }
    //后置通知 -- 代理方法执行完毕后执行
    @After("pt()")
    public void after() {
        System.out.println("UserDao save After");
    }
    // 环绕通知 -- 自定义代理方法执行顺序
    // ProceedingJoinPoint 是环绕通知必须得参数不可省略 
    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("UserDao Around Before");
        // 执行代理方法,如果没有-代理方法就无法执行
        proceedingJoinPoint.proceed();
        System.out.println("UserDao Around After");
        // 当被代理的方法有返回值时,必须要返回值,如果没有可以返回Object也可以设置void
        return new Object();
    }
    // 返回后通知 -- 代理方法执行后通知
    @AfterReturning("pt()")
    public void afterReturning() {
        System.out.println("UserDao AfterReturning");
    }
    // 抛出异常后通知 -- 代理方法执行异常后通知
    @AfterThrowing("pt()")
    public void afterThrowing() {
        System.out.println("UserDao AfterThrowing");
    }
}

​ (4)、测试执行

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    UserDao bookDao = ctx.getBean(UserDao.class);
    bookDao.save();
}
2、案例-测试业务层接口万次执行效率

​ (1)Spring配置类

@Configuration
@ComponentScan("top.newhand")
// 开启AOP自动代理,如果没有默认关闭AOP
@EnableAspectJAutoProxy
public class SpringConfig {
}

​ (2)编写业务

// 这里正常编写业务即可,无需其他特殊配置
public interface UserDao {
    void save();
}
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("book dao Save ...");
    }
}

​ (3)定义通知类,制作通知方法

// AOP通知类必须放入Ioc容器,所以一定要@Component 交由SPring管理
@Component
// @Aspect 定义通知类,如果没有不生效
@Aspect
public class DaoAdvice {
	// 定义切点位置,可以使用通配符, 定义切点方法pt()
    @Pointcut("execution(void top.newhand.dao.UserDao.save())")
    private void pt() {}
	// 制作通知方法,有五种
    // 环绕通知 -- 自定义代理方法执行顺序
    // ProceedingJoinPoint 是环绕通知必须得参数不可省略 
    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++ ){
            // 执行代理方法,如果没有-代理方法就无法执行
            proceedingJoinPoint.proceed();
        }
        long end = System.currentTimeMillis();
        //获取执行的签名对象
        Signature signature = proceedingJoinPoint.getSignature();
        //获取接口/类全限定名
        String className = signature.getDeclaringTypeName();
        //获取方法名
        String methodName = signature.getName();
        System.out.println("万次执行:"+ className+"."+methodName+"-->" +(end-start) + "ms");
        return new Object();
    }
}

​ (4)、测试执行

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    UserDao bookDao = ctx.getBean(UserDao.class);
    bookDao.save();
}

请添加图片描述

3、案例-百度网盘密码数据兼容处理

​ (1)、分析场景: 对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理
请添加图片描述

​ 分析:
​ ①:在业务方法执行之前对所有的输入参数进行格式处理——trim()
​ ②:使用处理后的参数调用原始方法——环绕通知中存在对原始方法的调用

​ (2)、Spring配置类

@Configuration
@ComponentScan("top.newhand")
// 开启AOP自动代理,如果没有默认关闭AOP
@EnableAspectJAutoProxy
public class SpringConfig {
}

​ (3)编写业务

// 这里正常编写业务即可,无需其他特殊配置
// Dao 代码
public interface ResourceDao {
    boolean readResources(String url, String password);
}
@Repository
public class ResourceDaoImpl implements ResourceDao {
    @Override
    public boolean readResources(String url, String password) {
        System.out.println(password.length());
        return "root".equals(password);
    }
}
// Service代码
public interface ResourceService {
    boolean openURL(String url, String password);
}
@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    @Override
    public boolean openURL(String url, String password) {
        return resourceDao.readResources(url, password);
    }
}

​ (4)定义通知类,制作通知方法

@Component
@Aspect
public class ResourceAdvice {
    @Pointcut("execution(boolean top.newhand.service.*Service.*(*,*))")
    public void servicePt(){
    }
    @Around("servicePt()")
    public Object trimStr(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //通过AOP获取切点方法参数,然后修改参数,利用 trim() 去掉字符串前后空格
        Object[] args = proceedingJoinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            //判断参数是不是字符串
            if(args[i].getClass().equals(String.class)){
                args[i] = args[i].toString().trim();
            }
        }
        return proceedingJoinPoint.proceed(args);
    }

}

​ (5)、测试执行

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    ResourceService resourcesService = ctx.getBean(ResourceService.class);
    boolean flag = resourcesService.openURL("http://pan.baidu.com/haha", "root ");
    System.out.println(flag);
}
pom文件
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.25.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.19</version>
</dependency>

代码地址:hexg8236/Demo: 各种项目Demo (github.com)

  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java-gang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值