1.什么是AOP?

AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充,它的主要编程对象是切面(aspect), 而切面模块化横切关注点.在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里。

2.为什么需要AOP?

越来越多的非业务需求(日志和验证等)加入后, 原有的业务方法急剧膨胀.  每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点. 以日志需求为例, 只是为了满足这个单一需求, 就不得不在多个模块(方法)里多次重复相同的日志代码. 如果日志需求发生变化, 必须修改所有模块。

上述问题解决的方法就是使用动态代理,代理设计模式的原理是使用一个代理将对象包装起来, 然后用该代理对象取代原始对象. 任何对原始对象的调用都要通过代理. 代理对象决定是否以及何时将方法调用转到原始对象上。

使用AOP的好处是:

  • 每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级
  • 业务模块更简洁, 只包含核心业务代码.

3.AOP术语

  • 切面(Aspect):  横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象;
  • 通知(Advice):  切面必须要完成的工作;
  • 目标(Target): 被通知的对象;
  • 代理(Proxy): 向目标对象应用通知之后创建的对象;
  • 连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如 ArithmethicCalculator#add() 方法执行前的连接点,执行点为 ArithmethicCalculator#add(); 方位为该方法执行前的位置;
  • 切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

4.如何使用AOP?

AspectJ:Java 社区里最完整最流行的 AOP 框架.在 Spring2.0 以上版本中, 可以使用基于 AspectJ 注解或基于 XML 配置的 AOP。

4.1 在Spring中启用AspectJ注解支持

(1)在classpath下添加jar包

要在Spring应用中使用AspectJ注解,需要添加的jar包有(包含Spring的基础jar包):

  • com.springsource.org.aopalliance-1.0.0.jar
  • com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  • commons-logging-1.1.3.jar
  • spring-aop-4.0.0.RELEASE.jar
  • spring-aspects-4.0.0.RELEASE.jar
  • spring-beans-4.0.0.RELEASE.jar
  • spring-context-4.0.0.RELEASE.jar
  • spring-core-4.0.0.RELEASE.jar
  • spring-expression-4.0.0.RELEASE.jar

(2)在配置文件中加入AOP的命名空间

(3)要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>,当 Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

4.2 用AspectJ注解声明切面

(1)要在Spring中声明AspectJ切面,需要在IOC容器中将切面声明为Bean实例,即加入@Component注解;

(2)在AspectJ注解中,切面是一个带有@Aspect注解的Java类,即加入@Aspect注解;

4.3 在类中声明各种通知

(1)声明一个方法;

(2)在方法前加入通知注解。

5.AspectJ 支持 5 种类型的通知注解

  • @Before: 前置通知, 在方法执行之前执行
  • @After: 后置通知, 在方法执行之后执行
  • @AfterRunning: 返回通知, 在方法返回结果之后执行
  • @AfterThrowing: 异常通知, 在方法抛出异常之后
  • @Around: 环绕通知, 围绕着方法执行

5.1 前置通知

在方法执行之前执行的通知。前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值。

示例代码:

定义接口:ArithmeticCalculator.java

  1. package com.java.spring.aop.impl;
  2.  
  3. public interface ArithmeticCalculator {
  4. int add(int i,int j);
  5. int sub(int i,int j);
  6. int mul(int i,int j);
  7. int div(int i,int j);
  8. }

接口的实现类:ArithmeticCalculatorImpl.java

  1. package com.java.spring.aop.impl;
  2. import org.springframework.stereotype.Component;
  3.  
  4. @Component("arithmetiCalculator")
  5. public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
  6. @Override
  7. public int add(int i, int j) {
  8. int result = i+j;
  9. return result;
  10. }
  11. @Override
  12. public int sub(int i, int j) {
  13. int result = i-j;
  14. return result;
  15. }
  16. @Override
  17. public int mul(int i, int j) {
  18. int result = i*j;
  19. return result;
  20. }
  21. @Override
  22. public int div(int i, int j) {
  23. int result = i/j;
  24. return result;
  25. }
  26. }

日志LoggingAspect.java

  1. package com.java.spring.aop.impl;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import org.aspectj.lang.JoinPoint;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.aspectj.lang.annotation.Before;
  8. import org.springframework.stereotype.Component;
  9. @Aspect
  10. @Component
  11. public class LoggingAspect {
  12. @Before("execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))")
  13. public void beforeMethod(JoinPoint joinpoint){
  14. String methodName=joinpoint.getSignature().getName();
  15. List<Object> args=Arrays.asList(joinpoint.getArgs());
  16. System.out.println("The method "+methodName+" begins with args "+args);
  17. }
  18.  
  19. }

在applicationContext.xml中进行配置:

  1. <context:component-scan base-package="com.java.spring.aop.impl"></context:component-scan>
  2. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试:

Main.java

  1. package com.java.spring.aop.impl;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. public class Main {
  7. public static void main(String[] args){
  8. ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
  9. ArithmeticCalculator ac=(ArithmeticCalculator) ctx.getBean("arithmetiCalculator");
  10. int result1=ac.add(123, 10);
  11. System.out.println(result1);
  12. int result2=ac.sub(123, 10);
  13. System.out.println(result2);
  14. }
  15. }

运行后输出:

  1. The method add begins with args [123, 10]
  2. 133
  3. The method sub begins with args [123, 10]
  4. 113

(1)LoggingAspect.java中,

  1. @Before("execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))")
    public void beforeMethod(JoinPoint joinpoint){...}

标示beforeMethod()方法是前置通知,切点表达式表示执行ArithmeticCalculator接口中参数为两个int类型,并且方法修饰符为public和返回值为int类型的所有方法。

最典型的切入点表达式时根据方法的签名来匹配各种方法:

  • execution * com.java.spring.aop.impl.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.
  • execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法.
  • execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中返回 double 类型数值的方法
  • execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数
  • execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法.

(2)让通知访问当前连接点的细节。可以在通知方法中声明一个类型为 JoinPoint 的参数. 然后就能访问链接细节. 如方法名称和参数值.

  1. String methodName=joinpoint.getSignature().getName();
  2. List<Object> args=Arrays.asList(joinpoint.getArgs());

5.2 后置通知

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候. 一个切面可以包括一个或者多个通知。

  1. @After("execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))")
  2. public void afterMethod(JoinPoint joinpoint){
  3. String methodName=joinpoint.getSignature().getName();
  4. List<Object> args=Arrays.asList(joinpoint.getArgs());
  5. System.out.println("The method "+methodName+" ends with args "+args);
  6. }

5.3 返回通知

无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知,返回通知是可以访问到方法的返回值的。

在返回通知中, 只要将 returning 属性添加到 @AfterReturning 注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称. 而且必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.

  1. @AfterReturning(value="execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))",
  2. returning="result")
  3. public void reutrnMethod(JoinPoint joinpoint,Object result){
  4. String methodName=joinpoint.getSignature().getName();
  5. List<Object> args=Arrays.asList(joinpoint.getArgs());
  6. System.out.println("The method "+methodName+" ends with args "+args+"and the result is "+result);
  7. }

5.4 异常通知

只在连接点抛出异常时才执行异常通知。将 throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常. Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行。

  1. @AfterThrowing(value="execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))",
  2. throwing="e")
  3. public void afterThrowing(JoinPoint joinpoint,Exception e){
  4. String methodName=joinpoint.getSignature().getName();
  5. List<Object> args=Arrays.asList(joinpoint.getArgs());
  6. System.out.println("The method "+methodName+" occurs "+args+e);
  7. }

5.5 环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点。对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint ,可以决定是否执行目标方法。它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点。在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行。

  1. @Around("execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))")
  2. public Object aroundMethod(ProceedingJoinPoint pjd){
  3. Object result=null;
  4. String methodName=pjd.getSignature().getName();
  5. try {
  6. //前置通知
  7. System.out.println("The method "+methodName+" begins with args "+Arrays.asList(pjd.getArgs()));
  8. //执行目标方法
  9. result=pjd.proceed();
  10. //返回通知
  11. System.out.println("The method "+"ends with "+result);
  12. } catch (Throwable e) {
  13. //异常通知
  14. System.out.println("The method occurs Exception "+e);
  15. }
  16. //后置通知
  17. System.out.println("The method ends");
  18. return result;
  19. }

6.切面的优先级

在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.实现 Ordered 接口, getOrder() 方法的返回值越小, 优先级越高;若使用 @Order 注解, 序号出现在注解中。

  1. @Aspect
  2. @Order(0)
  3. @Component
  4. public class LoggingAspect {}

7.重用切入点表达式

在 AspectJ 切面中, 可以通过 @Pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的。后面的其他通知直接使用方法名来引用当前的接入点表达式。

切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.

  1. //定义一个方法,用于声明一个切入点表达式
  2. @Pointcut("execution(public int com.java.spring.aop.impl.ArithmeticCalculator.*(int, int))")
  3. public void declareJointPointExpression(){}
  4. @Before("declareJointPointExpression()")
  5. public void beforeMethod(JoinPoint joinpoint){
  6. String methodName=joinpoint.getSignature().getName();
  7. List<Object> args=Arrays.asList(joinpoint.getArgs());
  8. System.out.println("The method "+methodName+" begins with args "+args);
  9. }

wx搜索“程序员考拉”,专注java领域,一个伴你成长的公众号!

最全的Spring AOP的更多相关文章

  1. Spring AOP统一日志 全量日志

    Spring AOP 切面@Around注解的具体使用 lichuangcsdn 2019-02-19 23:21:36 63936 收藏 61分类专栏: Spring 文章标签: Spring AO ...

  2. Spring AOP支持的AspectJ切入点语法大全

    原文出处:http://jinnianshilongnian.iteye.com/blog/1420691 Spring AOP支持的AspectJ切入点指示符 切入点指示符用来指示切入点表达式目的, ...

  3. Spring AOP中pointcut expression表达式解析

    Pointcut 是指那些方法需要被执行"AOP",是由"Pointcut Expression"来描述的. Pointcut可以有下列方式来定义或者通过&am ...

  4. 基于@AspectJ配置Spring AOP之一--转

    原文地址:http://tech.it168.com/j/2007-08-30/200708302209432.shtml 概述 在低版本Spring中定义一个切面是比较麻烦的,需要实现特定的接口,并 ...

  5. TinyFrame再续篇:整合Spring AOP实现日志拦截

    上一篇中主要讲解了如何使用Spring IOC实现依赖注入的.但是操作的时候,有个很明显的问题没有解决,就是日志记录问题.如果手动添加,上百个上千个操作,每个操作都要写一遍WriteLog方法,工作量 ...

  6. Spring AOP:面向切面编程,AspectJ,是基于注解的方法

    面向切面编程的术语: 切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象 通知(Advice): 切面必须要完成的工作 目标(Target): 被通知的对象 代理(Pr ...

  7. Spring AOP中pointcut expression表达式解析 及匹配多个条件

    Spring中事务控制相关配置: <bean id="txManager" class="org.springframework.jdbc.datasource.D ...

  8. spring aop expression简单说明

    <aop:config> <aop:pointcut id="userDAO" expression="execution(public * cn.da ...

  9. spring Aop 注解

    个人理解: spring Aop 是什么:面向切面编程,类似于自定义拦截操作,支持拦截之前操作@Before,拦截之后操作@After,拦截环绕操作@Around. 什么情况下使用spring Aop ...

随机推荐

  1. Redis的认识和基本操作

    Redis是什么 Redis 是一个高性能的开源的.C语言写的Nosql(非关系型数据库),数据保存在内存中. Redis 是以key-value形式存储的Nosql,和传统的关系型数据库不一样.不一 ...

  2. php批量导出pdf文件的脚本(html-PDf)

    背景:突然有大量的文件需要导出成PDF文件,写一个批量导出pdf的脚本,同时文件的命名也需要有一定的规则 导出方式:向服务器中上传csv文件,csv文件中包含文件的地址和相对应的文件命名. 如下格式: ...

  3. 使用.net core读取Json文件配置

    1.使用vs2017创建一个应用台程序 2.使用程序包管理器控制台执行命令 Install-Package Microsoft.AspNetCore -Version 2.0.1 3.创建一个json ...

  4. vue-cli新建vue项目安装axios后在IE下报错

    使用脚手架新建了一个vue项目,可以在IE9+浏览器运行,但是在添加了axios后,在IE下就报错了 首先是安装axios,在命令行执行: $ npm install axios -s //执行命令, ...

  5. thuwc2019总结

    275,是我的自己的估分 而350,是面试线 就发挥而言,这次的发挥相当糟糕,第一天选择全场打暴力而不打签到题正解,第二天因A题思路想偏造成2h额外时间花费.第二题与第三题之间,我选择了难打的第三题而 ...

  6. _new_()与_init_()的区别

    先上代码   其中,__new__()不是一定要有,只有继承自object的类才有,该方法可以return父类(通过super(当前类名, cls).__new__())出来的实例,或者直接是obje ...

  7. php 常见图片处理函数封装

    <?php /** * 常见图像处理函数的封装 */ class Image{ private $info=[]; private $width;//原始图片宽度 private $height ...

  8. 优化 JS 条件语句的 5 个技巧

    优化 JS 条件语句的 5 个技巧 原创: 前端大全 前端大全 昨天 (给前端大全加星标,提升前端技能) 编译:伯乐在线/Mr.Dcheng http://blog.jobbole.com/11467 ...

  9. python聚类算法实战详细笔记 (python3.6+(win10、Linux))

    python聚类算法实战详细笔记 (python3.6+(win10.Linux)) 一.基本概念:     1.计算TF-DIF TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库 ...

  10. MySQL命令行导入sql文件时出现乱码解决方案

    Note: sql> source F:weibo.sql(执行相关sql文件) sql> select * from sina into outfile "/weibo.txt ...