彻底弄懂Spring中的AOP(XML+注解)

一、AOP简介

1、AOP基本概念

在这里插入图片描述

简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强

2、AOP的作用及优势

作用:在程序运行期间,不修改源码对已有方法进行增强。
优势:减少重复代码;提高开发效率;维护方便

3、AOP 的实现方式

使用动态代理技术

4、AOP相关术语

(1)Joinpoint(连接点)

所谓连接点是指那些被拦截到的点。在 Spring 中,这些点指的是方法,因为 Spring 只支持方法类型的连接点。

(2)Pointcut(切入点)

所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。

注意:所有的切入点都是连接点,但是所有的连接点不一定都是切入点。

(3)Advice(通知/增强)

所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。

(4)Introduction(引介)

引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field。

(5)Target(目标对象)

代理的目标对象。

(6)Weaving(织入)

是指把增强应用到目标对象来创建新的代理对象的过程。
Spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。

(7)Proxy(代理)

一个类被 AOP 织入增强后,就产生一个结果代理类。

(8)Aspect(切面)

是切入点和通知(引介)的结合。

5、学习 Spring 中的 AOP 要明确的事

a、开发阶段(我们做的)
编写核心业务代码(开发主线):大部分程序员来做,要求熟悉业务需求。
把公用代码抽取出来,制作成通知。(开发阶段最后再做)
在配置文件中,声明切入点与通知间的关系,即切面。

b、运行阶段(Spring 框架完成的)
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

6、关于代理的选择

在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。

二、基于XML的AOP配置

1、添加依赖

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

2、IAccountService.java

public interface IAccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();

    /**
     * 模拟更新账户
     * @param i
     */
    void updateAccount(int i);

    /**
     * 模拟删除账户
     * @return
     */
    int deleteAccount();
}

3、AccountServiceImpl.java

public class AccountServiceImpl implements IAccountService {
    public void saveAccount() {
        System.out.println("执行了保存");
    }

    public void updateAccount(int i) {
        System.out.println("执行了更新" + i);
    }

    public int deleteAccount() {
        System.out.println("执行了删除");
        return 0;
    }
}

4、Logger.java

public class Logger {
    /**
     * 用于打印日志,计划让其在切入点方法执行之前执行(切入点方法即业务层方法)
     */
    public void printLog() {
        System.out.println("Logger类中的printLog方法开始记录日志了......");
    }
}

5、bean.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">

    <!--配置Spring的IoC,把accountService对象注入到容器中-->
    <bean id="accountService" class="com.uos.service.impl.AccountServiceImpl"></bean>

    <!--通知bean-->
    <bean id="logger" class="com.uos.utils.Logger"></bean>
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--配置通知的类型,并将建立通知的方法和切入点方法进行关联-->
            <aop:before method="printLog" pointcut="execution(* com.uos.service.impl.*.*(..))"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

在这里插入图片描述
在这里插入图片描述

6、AopTest.java

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService accountService = (IAccountService) applicationContext.getBean("accountService");
        accountService.saveAccount();
    }
}

7、运行结果

在这里插入图片描述

三、基于注解的AOP

本案例基于XML的AOP的案例进行配置。

1、添加@Service注解

在这里插入图片描述

2、配置切面类

@Component("logger")
@Aspect     //表示当前类是一个切面类
public class Logger {
    @Pointcut("execution(* com.uos.service.impl.*.*(..))")
    public void pt1(){};
    /**
     * 前置通知
     */
    //@Before("pt1()")
    public void beforePrintLog() {
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了......");
    }
    /**
     * 后置通知
     */
   // @AfterReturning("pt1()")
    public void afterPrintLog() {
        System.out.println("后置通知Logger类中的afterPrintLog方法开始记录日志了......");
    }
    /**
     * 异常通知
     */
  //  @AfterThrowing("pt1()")
    public void throwingPrintLog() {
        System.out.println("异常通知Logger类中的throwingPrintLog方法开始记录日志了......");
    }
    /**
     * 最终通知
     */
  //  @After("pt1()")
    public void finalPrintLog() {
        System.out.println("最终通知Logger类中的finalPrintLog方法开始记录日志了......");
    }
    /**
     * 环绕通知
     */
    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            // 得到方法执行所需的参数
            Object[] args = pjp.getArgs();
            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了......前置");

            // 明确调用业务层方法
            rtValue= pjp.proceed(args);

            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了......后置");
            return rtValue;
        } catch (Throwable t) {
            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了......异常");
            throw new RuntimeException(t);
        } finally {
            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了......最终");
        }

    }
}

3、bean.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"
       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">

    <!--告知Spring创建容器时需要扫描的包-->
    <context:component-scan base-package="com.uos"></context:component-scan>
    <!--配置Spring开启注解AOP的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值