Spring还可以这么学--AOP

Spring还可以这么学–AOP

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

1. 什么是AOP?

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

2. AOP的作用?

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

首先我们来看没有AOP时,如果我们要做日志处理,就得在每个方法中添加

《Spring还可以这么学--AOP》

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

《Spring还可以这么学--AOP》

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

使用AOP后

《Spring还可以这么学--AOP》

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

《Spring还可以这么学--AOP》

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

《Spring还可以这么学--AOP》

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.IllegalArgumentException
Exception 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;

@Aspect
public 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.IllegalArgumentException
Exception in thread "main" java.lang.IllegalArgumentException
......

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

QQ学习交流群:713479727
微信学习交流群:微信群加入方式【公众号下方菜单栏–>学习资源–>微信群】
微信公众号:EverydayCoding 或扫描下方二维码
欢迎大家加入。。。

《Spring还可以这么学--AOP》

    原文作者:sf_wangchong
    原文地址: https://segmentfault.com/a/1190000014800711
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞