图文结合分析Spring的面向切面编程–AOP

作者 : 开心源码 本文共6249个字,预计阅读时间需要16分钟 发布时间: 2022-05-12 共237人阅读

Spring还可以这么学–AOP

上一篇文章[浅显易懂]一文读懂Spring IoC(控制反转) / DI(依赖注入)

1. 什么是AOP?

AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。

2. AOP的作用?

利用一种称为”横切”的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用板块,并将其命名为”Aspect”,即切面。所谓”切面”,简单说就是那些与业务无关,却为业务板块所共同调用的逻辑或者责任封装起来,便于减少系统的重复代码,降低板块之间的耦合度,并有利于未来的可操作性和可维护性。

首先我们来看没有AOP时,假如我们要做日志解决,就得在每个方法中增加

但大多数日志解决代码都是相同的,所以我们将日志解决抽离成一个新的方法,但是虽然这样,我们还得手动插入这些方法。

但这样代码的耦合度很高,当我们要更改这个功能时,就得一个个更改

使用AOP后

为了在指定位置执行这些横向的功能,需要知道指定的是什么地方

例如上图,方法级别的aop实现,在一个程序执行链条中,把method2称为切点,也就是说在method2执行时会执行横切的功能,那么是在method2之前还是之后呢,又是执行什么呢?这些都由advice(通知)来指定。
Spring 方面可以使用下面提到的五种通知工作:

3. AOP的核心概念

  • 横切关注点:对哪些方法进行阻拦,阻拦后怎样解决,这些关注点称之为横切关注点
  • 切面(aspect):类是对物体特征的笼统,切面就是对横切关注点的笼统
  • 连接点(joinpoint):被阻拦到的点,由于Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被阻拦到的方法,实际上连接点还可以是字段或者者构造器
  • 切入点(pointcut):对连接点进行阻拦的定义
  • 通知(advice):所谓通知指的就是指阻拦到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
  • 目标对象:代理商的目标对象
  • 织入(weave):将切面应用到目标对象并导致代理商对象创立的过程
  • 引入(introduction):在不修改代码的前提下,引入可以在运行期为类动态地增加少量方法或者字段

4. 实现方式

Spring AOP的XML实现方式

Employee.java文件

package com.wangc;public class Employee {    private String name;    private int age;    public String getName() {        System.out.println("name = "+name);        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        System.out.println("age = "+age);        return age;    }    public void setAge(int age) {        this.age = age;    }    public void printThrowException() {        System.out.println("发生异常");        throw new IllegalArgumentException();    }}

Logging.java文件

package com.wangc;public class Logging {    //在一个方法执行之前,执行通知。    public void beforeAdvice(){        System.out.println("执行employee的方法之前执行.");    }    //在一个方法执行之后,不考虑其结果,执行通知。    public void afterAdvice(){        System.out.println("执行employee的方法之后执行.");    }    //在一个方法执行之后,只有在方法成功完成时,才能执行通知。    public void afterReturningAdvice(Object retVal){        System.out.println("返回:" + retVal.toString() );    }    //在一个方法执行之后,只有在方法退出抛出异常时,才能执行通知。    public void AfterThrowingAdvice(IllegalArgumentException ex){        System.out.println("抛出了一个异常: " + ex.toString());       }  }

Beans.xml文件

<?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:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">   <aop:config>      <!-- 公告一个aspect,logging将被依赖注入 -->      <aop:aspect id="log" ref="logging">         <!-- 公告一个切入点 ,该切入点将与 com.wangc 包下的Logging类的方法相匹配,这里的“*”是通配符-->         <aop:pointcut id="all" expression="execution(* com.wangc.*.*(..))"/>         <!-- 定义一个前置通知 -->         <aop:before pointcut-ref="all" method="beforeAdvice"/>         <!-- 定义一个后置通知 -->         <aop:after pointcut-ref="all" method="afterAdvice"/>         <!-- 定义一个返回后通知 -->         <aop:after-returning pointcut-ref="all" returning="retVal" method="afterReturningAdvice"/>         <!-- 定义一个抛出异常后通知 -->         <aop:after-throwing pointcut-ref="all" throwing="ex" method="AfterThrowingAdvice"/>      </aop:aspect>   </aop:config>   <bean id="employee" class="com.wangc.Employee">      <property name="name"  value="zhangsan" />      <property name="age"  value="28" />         </bean>   <bean id="logging" class="com.wangc.Logging"/> </beans>

MyApp.java文件

package com.wangc;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyApp {    public static void main(String[] args) {        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");        Employee employee = (Employee) context.getBean("employee");        employee.getName();        employee.getAge();        employee.printThrowException();    }}

执行结果:

执行employee的方法之前执行.name = zhangsan执行employee的方法之后执行.返回:zhangsan执行employee的方法之前执行.age = 28执行employee的方法之后执行.返回:28执行employee的方法之前执行.发生异常执行employee的方法之后执行.抛出了一个异常: java.lang.IllegalArgumentExceptionException in thread "main" java.lang.IllegalArgumentException......

注意:上面的例子只有一个横切关注点,假如有多个横切关注点,可以使用aspect里的order属性来控制横切关注点的顺序。

......   <aop:config>      <aop:aspect id="log1" ref="logging1" order="1">         <aop:pointcut id="addTime" expression="execution(* com.wangc.*.*(..))"/>         <aop:before pointcut-ref="addTime" method="beforeAdvice"/>      </aop:aspect>      <aop:aspect id="log2" ref="logging2" order="2">         <aop:pointcut id="printLog" expression="execution(* com.wangc.*.*(..))"/>         <aop:before pointcut-ref="printLog" method="beforeAdvice"/>      </aop:aspect>   </aop:config>   ......

Spring AOP 的 @AspectJ实现方式

这里只要要在上面的基础上修改以下两个文件即可实现,修改后的文件如下:
Beans.xml文件

<?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:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">    <!-- 自动扫描被@Aspect标注的切面 -->    <aop:aspectj-autoproxy />    <bean id="employee" class="com.wangc.Employee">       <property name="name"  value="zhangsan" />       <property name="age"  value="28" />          </bean>    <bean id="logging" class="com.wangc.Logging"/> </beans>

Logging.java文件

package com.wangc;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;@Aspectpublic class Logging {    @Pointcut("execution(* com.wangc.*.*(..))")    private void all() {    }    //在一个方法执行之前,执行通知。    @Before("all()")    public void beforeAdvice(){        System.out.println("执行employee的方法之前执行.");    }    //在一个方法执行之后,不考虑其结果,执行通知。    @After("all()")    public void afterAdvice(){        System.out.println("执行employee的方法之后执行.");    }    //在一个方法执行之后,只有在方法成功完成时,才能执行通知。    @AfterReturning(pointcut = "all()", returning="retVal")    public void afterReturningAdvice(Object retVal){        System.out.println("返回:" + retVal.toString() );    }    //在一个方法执行之后,只有在方法退出抛出异常时,才能执行通知。    @AfterThrowing(pointcut = "all()", throwing="ex")    public void AfterThrowingAdvice(IllegalArgumentException ex){        System.out.println("抛出了一个异常: " + ex.toString());       }  }

这里做个简单的说明: 用@Aspect的注解来标识切面,注意不要把它漏了,否则Spring创立代理商的时候会找不到它,@Pointcut注解指定了切点,@Before、@After、@AfterReturning和@AfterThrowing指定了运行时的通知。

运行结果:

执行employee的方法之前执行.name = zhangsan执行employee的方法之后执行.返回:zhangsan执行employee的方法之前执行.age = 28执行employee的方法之后执行.返回:28执行employee的方法之前执行.发生异常执行employee的方法之后执行.抛出了一个异常: java.lang.IllegalArgumentExceptionException in thread "main" java.lang.IllegalArgumentException......

上一篇文章Spring还可以这么学–IoC(控制反转) / DI(依赖注入)了解


我的个人微信公众号:Java编程社区 欢迎大家加入。。。

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 图文结合分析Spring的面向切面编程–AOP

发表回复