Spring学习笔记(六)——面向切面编程AOP

什么是AOP ?

AOP(Aspect Orient Programming) 意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

为什么要用AOP ?

AOP也是一种编程思想,能保证开发者不修改源代码的前提下,去为系统中的业务组件添加某种通用功能。

使用场景:日志记录、权限验证、效率检查、事务管理…

传统OOP是自上而下的逻辑开发,AOP是一种面向切面的编程思想,这些横切性问题,把它们抽象为一个切面,关注点在切面的编程,这就是所谓的AOP。
在这里插入图片描述
Spring AOP 可以提供声明式事务,允许用户自定义切面

Spring实现AOP的三种方式:

首先我们了解几个AOP术语:

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
  • 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法
  • 目标(Target):被通知对象
  • 代理(Proxy):向目标对象应用通知之后创建的对象
  • 切入点(PointCut):切面通知执行的“地点”的定义
  • 连接点(JointPoint):与切入点匹配的执行点

创建一个UserService接口:

public interface UserService {
    public void add();
    public void delete();
}

创建UserService实现类UserServiceImpl:

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("增加一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除一个用户");
    }
}

配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userService" class="service.UserServiceImpl"></bean>
</beans>

测试:
在这里插入图片描述
此时如果我们想要在每次UserServiceImpl调用方法时打印一些日志信息,应该怎么实现呢?我们可以使用动态代理模式,代理UserService接口,同时代理类增加打印日志信息的方法,在Spring中就可以使用AOP来实现,因为AOP就是通过动态代理实现的。

① 使用原生Spring API 接口实现AOP

创建一个beforeLog类实现MethodBeforeAdvice接口,重写MethodBeforeAdvice接口的before方法,这个方法将在调用目标方法前执行。

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class beforeLog implements MethodBeforeAdvice {
    // 在目标方法执行前执行这个方法
    //method : 要执行的目标对象的方法
    //args : 参数
    //target :目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

创建一个afterLog类实现AfterReturningAdvice接口,重写AfterReturningAdvice接口的afterReturning方法,这个方法将在调用的目标方法返回结果后执行。

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class afterLog implements AfterReturningAdvice {
    // 在目标方法返回结果后执行这个方法
    //returnValue :返回的结果
    //method : 要执行的目标对象的方法
    //args : 参数
    //target :目标对象
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
    }
}

修改配置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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="service.UserServiceImpl"></bean>
    <bean id="afterLog" class="log.afterLog"></bean>
    <bean id="beforeLog" class="log.beforeLog"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--切入点:expression表达式-->
        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>
</beans>

测试:

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // Spring实现AOP采用的是动态代理,动态代理代理的是接口,所以这里必须是UserService.class
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        userService.delete();
    }

结果:
在这里插入图片描述

② 自定义切面实现AOP

创建一个自定义切面类:

// 自定义切面
public class DiyPointCut {
    public void before(){
        System.out.println("=====方法执行前=====");
    }
    public void after(){
        System.out.println("=====方法执行后=====");
    }
}

修改配置文件:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="service.UserServiceImpl"></bean>

    <bean id="diyPointCut" class="diy.DiyPointCut"></bean>
    <!--配置AOP-->
    <aop:config>
        <!--自定义切面-->
        <aop:aspect ref="diyPointCut">
            <!--切入点:expression表达式-->
            <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"></aop:before>
            <aop:after method="after" pointcut-ref="point"></aop:after>
        </aop:aspect>
    </aop:config>
</beans>

测试输出:
在这里插入图片描述

这种方法无法像使用原生Spring API 接口一样得到代理对象的信息
③ 使用注解实现AOP

创建一个自定义切面类:

@Aspect //  标记这个类为一个切面
public class AnnotationPointCut {
    @Before("execution(* service.UserServiceImpl.*(..))") // 标记在目标方法执行前执行下面这个方法
    public void before(){
        System.out.println("--------方法执行前--------");
    }
    
    @After("execution(* service.UserServiceImpl.*(..))") // 标记在目标方法执行后执行下面这个方法
    public void after(){
        System.out.println("--------方法执行后--------");
    }
    
    @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前...");
        Object proceed = joinPoint.proceed(); // 执行方法
        Signature signature = joinPoint.getSignature(); // 获取签名,即目标方法的信息
        System.out.println(signature);
        Object target = joinPoint.getTarget(); // 获取目标对象
        System.out.println(target);
        System.out.println("环绕后...");
    }
}

修改配置文件:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="service.UserServiceImpl"></bean>

    <bean id="annotationPointCut" class="diy.AnnotationPointCut"></bean>
    <!--开启AOP自动代理-->
    <aop:aspectj-autoproxy/>
</beans>

测试输出:
在这里插入图片描述
注意:

  • 被@Around注解的方法必须加上ProceedingJoinPoint参数,通过它显示地调用目标方法,也可通过它获取代理对象的信息
  • ProceedingJoinPoint参数只有在被@Around注解的方法上有效,在其他方法上使用会报错
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值