Spring5之面向切面编程(AoP)

目录

前言

一、AoP的特点及功能

二、AoP的原理及JDK动态代理

三、基于注解的方式实现AoP

1、Aop的相关术语

2、导入相关依赖

3、进行AOP操作 

四、基于配置文件的方式实现AoP


前言

前面讲过IoC操作bean管理,这里主要对Spring的另一核心AoP做个描述。AoP:面向切面编程,它可以在不通过修改源代码的基础之上,在主干功能里增加新的功能。

一、AoP的特点及功能

1、特点:利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

2、主要功能:日志记录,性能统计,安全控制,事务处理,异常处理等等。

二、AoP的原理及JDK动态代理

1、aop底层用了动态代理,有两种情况的动态代理:

第一种 有接口的情况,使用JDK动态代理,创建接口实现类代理对象,增加类的方法。

第二种 没有接口的情况,使用CGLIB动态代理,创建当前类子类的代理对象,增加类的方法。

2、JDK动态代理

(1)使用JDK动态代理,使用Proxy类里面的方法创建代理对象

 (2)调用newProxyInstance方法

方法里有三个参数:第一个参数表示类加载器。第二个参数表示增强方法所在的类,这个类实现的接口,支持多个接口。第三个参数表示实现接口InvocationHandler,创建代理对象,写增强的方法

三、基于注解的方式实现AoP

1、Aop的相关术语

(1)连接点

类里面哪些方法可以被增强,这些方法称为连接点

(2)切入点

实际被真正增强的方法,称为切入点

(3)通知(增强)

实际增强的逻辑部分称为通知(增强),比如登录功能中的权限判断

通知有多种类型,如下所示:

前置通知:@Before

后置通知:@AfterReturning(返回通知)

环绕通知:@Around

异常通知:@AfterThrowing

最终通知:@After(无论程序出不出现异常,其都会出现,且出现在被增强方法之后,所以称为最终通知)

(4)切面

把通知应用到切入点的过程,比如将权限判断加入进登录方法中

(5)切入点表达式

切入点表达式的作用:知道对哪个类里面的哪个方法进行增强。语法结构如下:

execution(【权限修饰符】【返回类型】【类全路径】【方法名称】(【参数列表】))

@Before(value = "execution(* com.aopanno.User.add(..))")

权限修饰符可以不写,但返回值必须要写,*表示任意返回类型,它必须要与类全路径名用空格隔开,add表示要增强的方法,“..”表示参数列表 。

2、导入相关依赖

Spring框架一般都是基于AspectJ实现AOP操作的。AspectJ不是Spring的组成部分,它是一个独立的AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作。所以要导入AspectJ的jar包。

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3、进行AOP操作 

(1)创建类,该类为被增强类,在类里面定义方法

package com.aopanno;
public class User {
    public void add() {
        System.out.println("add......");
    }
}

(2)创建增强类(编写增强逻辑),在增强类里面,创建方法,让不同的方法代表不同通知类型

//增强的类
public class UserProxy {
    public void before() {
        System.out.println("before......");
    }
    public void after(){
        System.out.println("after........");
    }
    public void afterReturning(){
        System.out.println("afterReturning........");
    }
    public void afterThrowing(){
        System.out.println("afterThrowing");
    }
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前......");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后......");
    }
}

 (3)进行通知的配置

在spring文件中先开启注解扫描:

<context:component-scan base-package="com.aopanno"/>

使用注解创建User和UserProxy对象,并在增强的类上面添加注解@Aspect

@Component
@Aspect  //生成代理对象

在spring配置文件中开启生成代理对象

<aop:aspectj-autoproxy/>

配置不同类型的通知,在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式进行配置。

@Component
@Aspect  //生成代理对象
public class UserProxy {
    //前置通知,里面用切入点表达式
    @Before(value = "execution(* com.aopanno.User.add(..))")
    public void before() {
        System.out.println("before......");
    }
    //在方法之后执行,无论异常与否都执行
    @After(value = "execution(* com.aopanno.User.add(..))")
    public void after(){
        System.out.println("after........");
    }
    //在返回值之后执行,只有在方法正常返回的情况下才执行
    @AfterReturning(value = "execution(* com.aopanno.User.add(..))")
    public void afterReturning(){
        System.out.println("afterReturning........");
    }
    @AfterThrowing(value = "execution(* com.aopanno.User.add(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing");
    }
    @Around(value = "execution(* com.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前......");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后......");
    }
}

(4) 对相同的切入点进行抽取

大家会发现切入点的表达式都是一样的,那如何对相同的切入点进行抽取呢?类似于静态方法,该方法可以被共享,所以我们定义一个方法,将切入点表达式放入该方法中,只需调用该方法即可。此种做法方便代码的后期维护,比如切入点表达式发生变化,无需一个个费劲地去改,只需改方法里的代码。

@Component
@Aspect  //生成代理对象
public class UserProxy {
    //相同切入点抽取
    @Pointcut(value ="execution(* com.aopanno.User.add(..))")
    public void pointDemo(){
    }

    //前置通知,里面用切入点表达式
    @Before(value = "pointDemo()")
    public void before() {
        System.out.println("before......");
    }
    //在方法之后执行,无论异常与否都执行
    @After(value = "pointDemo()")
    public void after(){
        System.out.println("after........");
    }
    //在返回值之后执行,只有在方法正常返回的情况下才执行
    @AfterReturning(value = "pointDemo()")
    public void afterReturning(){
        System.out.println("afterReturning........");
    }
    @AfterThrowing(value = "pointDemo()")
    public void afterThrowing(){
        System.out.println("afterThrowing");
    }
    @Around(value = "pointDemo()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前......");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后......");
    }
}

 (5)结果分析

从结果可以看出每个通知的执行 。前置通知before,作用在被增强方法add方法的前面,环绕通知around,围绕add方法,并且在前置通知和最终通知之前,最终通知after作用在后置通知afterReturning之前,此外我们还发现,异常通知还未出现。假设程序出现异常,每个通知的执行顺序又会有怎样的变化呢?

 当出现异常时,异常通知afterThrowing出现,且最终通知after出现,这也是它为什么叫最终通知了。

(6)当有多个增强类对同一个方法进行增强,可以设置增强类的优先级

在增强类上面添加注解@Order(数字值),数字越小,优先级就越高,再创建一个增强方法:

package com.aopanno;

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

@Component
@Aspect
@Order(1)
public class PersonProxy {
    @Before(value = "execution(* com.aopanno.User.add(..))")
    public void before() {
        System.out.println("Person Before......");
    }

}
@Order(2)
@Component
@Aspect  //生成代理对象
public class UserProxy {
    //相同切入点抽取
    @Pointcut(value ="execution(* com.aopanno.User.add(..))")
    public void pointDemo(){
    }

结果如下:

(7)完全注解开发

创建配置类,不需要创建xml配置文件,@Configuration,添加此注解,系统就知道这是配置类,@ComponentScan,表示开启注解扫描,@EnableAspectJAutoProxy,开启Aspect生成代理对象

package com.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages = {"com"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}
@Test
    public void test(){
        ApplicationContext context=new AnnotationConfigApplicationContext(ConfigAop.class);
        User user = context.getBean("user", User.class);
        user.add();

    }

需要注意的是,Junit测试单元写法有点不同,后面表示加载注解配置文件 

四、基于配置文件的方式实现AoP

基于配置文件的方式稍微了解即可

1、创建两个类,增强类和被增强类,然后再创建方法

package com.aopxml;

public class Book {
    public void buy(){
        System.out.println("buy.........");
    }

}
package com.aopxml;

public class BookProxy {
    public void before() {
        System.out.println("before.......");
    }

}

2、在spring配置文件中创建两个类的对象

<bean id="book" class="com.aopxml.Book"></bean>
<bean id="bookProxy" class="com.aopxml.BookProxy"></bean>

3、在spring配置文件中配置切入点,并以前置通知@before为例

<!--配置aop增强-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="point" expression="execution(* com.aopxml.Book.buy(..))"/>
        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

4、 编写测试类

@Test
    public void testAopXml() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }

5、结果

猜你喜欢

转载自blog.csdn.net/qq_53860947/article/details/123997831