Spring Aop

本文介绍了Spring AOP相关知识。AOP是将重复代码抽象成切面类,运行时动态植入业务方法。先介绍了代理模式,包括静态、动态和Cglib代理。接着阐述了Xml和注解两种方式实现AOP,还进行了增强拓展测试,指出被切对象在Spring容器中是代理对象。

目录

Aop简介

Xml方式实现Aop

增强拓展

注解方式实现Aop

 

 

 

Aop简介

Aop面向切面的编程,就是把很多功能重复的代码抽象出来形成切面类代码,再有运行时向业务方法中动态植入切面类代码。

关注点:重复的代码

切面:关注点形成的类叫切面类

切入点:植入切面类代码的地方,通过切入点表达式,指定拦截哪些类的哪些方法,在这里植入切面类代码。

在介绍spring Aop之前,先介绍下代理模式。

静态代理:https://blog.youkuaiyun.com/weixin_39143647/article/details/91133477

动态代理:https://blog.youkuaiyun.com/weixin_39143647/article/details/91156582

Cglib代理:https://blog.youkuaiyun.com/weixin_39143647/article/details/93379126

Xml方式实现Aop

//建立业务类
public class Bank {
    public void transfer(String fromUser, String toUser, Double monney) {
        System.out.println("银行转账:" + fromUser + "转给" + toUser + "一共" + monney + "元");
    }
}
//构造切面类
public class BankTransferAop {
    public  void transferBefore(){
        System.out.println("开始转账");
    }
    public  void transferAfter(){
        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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="bank" class="com.spring.ljj.aop.Bank"></bean>
    <bean id="myBankTransferAop" class="com.spring.ljj.aop.BankTransferAop"></bean>
    <aop:config>
        <!--定义切点,切到哪里-->
        <!-- execution(* com.spring.ljj.aop.Bank.*(..)表示切到Bank类中的所有方法-->
        <!-- execution(* com.spring.ljj.aop..*.*(..)表示切到aop包及子包所有类中的所有方法-->
        <!-- execution(* com.spring.ljj.aop..*.save*(..)表示切到aop包及子包所有类中的所有  save开头的方法-->
        <!-- 第一个*代表方法的修饰符和返回类型,第二个*代表Bank中的所有方法,..代表一个或多个参数-->
        <aop:pointcut id="myPointCut" expression="execution(* com.spring.ljj.aop.Bank.transfer(..))"/>
        <!--定义切面类-->
        <aop:aspect id="myAspect" ref="myBankTransferAop">
            <!-- 配置切面类中的方法哪些是前置增强,哪些是后置增强,以及在哪个地方执行这些增强-->
            <!-- 不管核心方法是否抛出异常,增强都会执行(不可能异常了就不关闭数据库连接了)-->
            <aop:before method="transferBefore" pointcut-ref="myPointCut"></aop:before>
            <aop:after method="transferAfter" pointcut-ref="myPointCut"></aop:after>
        </aop:aspect>
    </aop:config>
</beans>

测试:

public class TestAop {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config2.xml");
        Bank bank = (Bank) context.getBean("bank");
        bank.transfer("Mike", "Lucy", 1000.0);
    }
}

运行结果:实现了前置和后置增强

增强拓展

//业务类
public class Bank {
    public boolean transfer(String fromUser, String toUser, Double monney){
        System.out.println("银行转账:" + fromUser + "转给" + toUser + "一共" + monney + "元");
        return true;
    }
}
//切面类

public class BankTransferAop {
    /**
     * 1.前置增强和后置增强(只有这俩个增强能拿到JoinPoint joinPoint):
     * <aop:before method="transferBefore2" pointcut-ref="myPointCut"></aop:before>
     * <aop:after method="transferBefore2" pointcut-ref="myPointCut"></aop:after>
     * <p>
     * 1.<aop:before method=和<aop:after method使用的方法都不能拿到返回类型
     * 原因:ProceedingJoinPoint proceedingJoinPoint获取不到,如果在前置和后置增强
     * 方法参数里写上ProceedingJoinPoint proceedingJoinPoint,启动就直接报错了)
     *
     * @param joinPoint:切点
     */
    public boolean transferBefore(JoinPoint joinPoint) {
        System.out.println("我是前置增强<aop:before ----------");
        Signature signature = joinPoint.getSignature();
        //拦截到的方法名
        System.out.println(signature.getName());
        //拦截的方法的参数
        System.out.println(Arrays.toString(joinPoint.getArgs()));
        return true;
    }
  public boolean transferAfter(JoinPoint joinPoint) {
        System.out.println("我是后置增强<aop:after -----------");
        Signature signature = joinPoint.getSignature();
        //拦截到的方法名
        System.out.println(signature.getName());
        //拦截的方法的参数
        System.out.println(Arrays.toString(joinPoint.getArgs()));
        return true;
    }

    /**
     * 2.可以拿到返回值的增强
     * <aop:after-returning method="afterReturn" pointcut-ref="myPointCut" returning="res"/>
     *
     * @param res:只有<aop:after-returning method指定的方法,系统可以自动注入进来此参数(返回结果)
     */
    public void afterReturn(Object res) {
        System.out.println("我是<aop:after-returning增强----------");
        System.out.println("结果为" + res);
    }


    /**
     * 3.环绕增强:环绕增强可以同时实现前置,后置,还可以拿到返回值
     * <aop:around method="around" pointcut-ref="myPointCut"></aop:around>
     *
     * @param proceedingJoinPoint:只有<aop:around method指定的方法可以自动注入进来此参数
     * @return
     * @throws Throwable
     */
    public boolean around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("我是环绕增强<aop:around----------");
        System.out.println("执行前置增强");
        //返回结果
        Object proceed = proceedingJoinPoint.proceed();
        System.out.println("执行后置增强");
        System.out.println(proceed);
        return true;
    }

    /**
     * 4异常增强:
     * 只有异常才会执行的方法,没有异常不会执行,其他增强都是无论有没有异常都会执行
     *
     * <aop:after-throwing method="disposeException" pointcut-ref="myPointCut" throwing="e"/>
     * @param e :只有<aop:after-throwing 指定的方法系统会自动注入此参数
     */
    public void disposeException(Exception e) {
        System.out.println("我是异常增强<aop:after-throwing----------");
        System.out.println(e.getMessage());
    }

}

配置:

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="bank" class="com.spring.ljj.aop.Bank"></bean>
    <bean id="myBankTransferAop" class="com.spring.ljj.aop.BankTransferAop"></bean>
    <aop:config>
        <aop:pointcut id="myPointCut" expression="execution(* com.spring.ljj.aop.Bank.*(..))"/>
        <aop:aspect id="myAspect" ref="myBankTransferAop" order="1">
            <!-- 前置增强,有没有异常都执行-->
            <aop:before method="transferBefore" pointcut-ref="myPointCut"></aop:before>
            <!-- 后置增强,有没有异常都执行-->
            <aop:after method="transferAfter" pointcut-ref="myPointCut"></aop:after>
            <!--可以拿到返回值的增强,没有异常才会执行returning="res"指的是afterReturn的Object res参数-->
            <aop:after-returning method="afterReturn" pointcut-ref="myPointCut" returning="res"/>
            <!-- 环绕增强,有没有异常都执行,是前3个增强的综合,可以实现前置,后置,还可以拿到返回值-->
            <aop:around method="around" pointcut-ref="myPointCut"></aop:around>
            <!-- 异常增强,有异常才会执行 throwing="e"指的是:disposeException方法参数e-->
            <aop:after-throwing method="disposeException" pointcut-ref="myPointCut" throwing="e"/>
        </aop:aspect>
    </aop:config>
</beans>

测试类:

public class TestAop {
    public static void main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config2.xml");
        Bank bank = (Bank) context.getBean("bank");
        bank.transfer("Mike", "Lucy", 1000.0);
    }
}

运行结果:没有异常,异常增强不执行

只修改业务类抛出异常:

public class Bank {
    public boolean transfer(String fromUser, String toUser, Double monney){
        System.out.println("银行转账:" + fromUser + "转给" + toUser + "一共" + monney + "元");
        System.out.println(1/0);
        return true;
    }
}

测试代码运行结果:有了异常增强照样执行,只有after-returnnig不执行

注解方式实现Aop

//业务类
@Service
public class Bank {
    public boolean transfer(String fromUser, String toUser, Double monney) {
        System.out.println("银行转账:" + fromUser + "转给" + toUser + "一共" + monney + "元");
        return true;
    }
}
//切面类
@EnableAspectJAutoProxy
@Aspect
@Component
public class BankTransferAop {
    @Before("execution(* com.spring.ljj.aop.annatation.Bank.transfer(..))")
    public void before() {
        System.out.println("我是前置增强");
    }
}

//配置文件里配置扫描注解:<context:component-scan base-package="com.spring.ljj"/>

//测试类
public class TestAop {
    public static void main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config3.xml");
        Bank bank = (Bank) context.getBean("bank");
        bank.transfer("Mike", "Lucy", 1000.0);
    }
}

运行结果:

 

 

 

 

注解Aop优化:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * @EnableAspectJAutoProxy:开启自动切面代理,默认是jdk动态代理,EnableAspectJAutoProxy(proxyTargetClass = true)即Cglib代理
 * @Aspect:标注此类是切面类
 * @Component:受spring容器管理 切面类
 */
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Aspect
@Component
public class BankTransferAop {
    /**
     * 定义切点
     */
    @Pointcut("execution(* com.spring.ljj.aop.annatation.Bank.transfer(..))")
    public void pointCut() {
    }

    /**
     * 定义前置增强
     */
    @Before("BankTransferAop.pointCut()")
    public void before() {
        System.out.println("我是前置增强");
    }

    /**
     * 定义环绕增强
     */
    @Around("BankTransferAop.pointCut()")
    public boolean around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("我是环绕增强");
        System.out.println("执行前置代码");
        boolean proceed = (Boolean) proceedingJoinPoint.proceed();
        System.out.println("执行后置代码");
        return proceed;
    }
}

再次测试运行结果:

public class TestAop {
    public static void main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config3.xml");
        System.out.println( context.getBean("bank").getClass());
    }
}

不管是xml还是注解实现的Aop,被切到的对象在Spring容器中都是代理对象:

 

###Spring AOP 的概念 AOP(Aspect-Oriented Programming)即面向切面编程,是一种编程范式,旨在通过分离横切关注点来提高模块化程度。在 Spring 框架中,AOP 被广泛用于实现诸如日志记录、事务管理、安全性等通用功能,这些功能通常与业务逻辑无关但又需要在多个地方重复使用。 Spring AOP 主要是基于 AspectJ 实现的,尽管 AspectJ 是一个独立的 AOP 框架,并不是 Spring 的组成部分,但它通常与 Spring 一起使用以提供更强大的 AOP 功能[^1]。Spring AOP 支持两种方式来定义切面:基于 XML 配置文件的方式和基于注解的方式。 ###Spring AOP 的原理 Spring AOP 使用运行时代理来实现 AOP 功能,这意味着它会在运行时动态生成代理对象。对于实现了接口的类,Spring AOP 默认使用 JDK 动态代理;而对于没有实现接口的类,则会使用 CGLIB 代理[^4]。这种方式允许在不修改原始代码的情况下向程序中添加新的行为。 织入(Weaving)是将增强(advice)应用到目标对象的过程,Spring AOP 在运行时进行织入操作[^3]。当创建了代理对象后,所有对目标对象方法的调用都会被拦截,并且可以插入额外的操作,比如在方法执行前后做一些处理。 ###Spring AOP 的使用教程 要开始使用 Spring AOP,首先需要确保项目中包含了必要的依赖。如果使用 Maven 构建工具,可以在 `pom.xml` 文件中加入如下依赖: ```xml <!-- 引入aop依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 一旦添加了依赖并刷新了 Maven 项目,就可以开始编写切面了。下面是一个简单的例子,展示如何使用注解来定义一个切面: ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Method " + joinPoint.getSignature().getName() + " is called."); } } ``` 在这个示例中,`LoggingAspect` 类被标记为 `@Aspect` 和 `@Component` 注解,这样 Spring 就能识别这是一个切面组件。`@Before` 注解指定了在哪些方法上应用前置通知(before advice),这里的表达式表示匹配 `com.example.service` 包下所有的方法。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值