spring基于xml的aop

我们有一个utils包,该包中有一个Logger类,该类有一个模拟打印日志的方法
在这里插入图片描述

如果我们想要每一次在执行业务层的方法前都执行该类的打印日志的方法,我们应该怎么办呢?

业务层接口如下
在这里插入图片描述
业务层实现类如下
在这里插入图片描述
很简单我们只需要利用动态代理的方式,动态代理业务层的实现类,动态增强该实现类中的切入点方法,实现在执行接口中的方法前执行打印日志的这个方法就可以了,但是这样很不方便,那我们如何使用spring的xml配置来实现这个功能呢?

使用spring的xml配置实现

首先导入spring-aop的xml配置的依赖坐标

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

然后创建xml文件导入aop的约束

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

1、把通知Bean也交给spring来管理

2、使用<aop:config>标签来表明开始aop配置

3、使用<aop:aspect>标签表明配置切面

  • id属性:是给切面提供的一个唯一标识
  • ref属性:指定通知类bean的id

4、在<aop:aspect>标签的内部使用对应的标签来配置通知的类型
我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知

<aop:before>:标识配置前置通知

  • method属性:用于指定Logger类中哪个方法是前置通知
  • pointcut属性:用于指定切入点表达式,该表达式的含义是对业务层中哪些方法的增强

切入点表达式的写法:
关键字:execution(表达式)
表达式:
访问修饰符 返回值 包名.包名...类名.方法名(参数列表)
标准的表达式写法:
public void com.hegong.service.impl.AccountService()

举例示范
在这里插入图片描述

问题

在使用xml配置前置通知、返回通知、最终通知时会出现一个执行顺序的的问题。最终通知再返回通知之前执行。

posted @ 2021-01-18 20:32  谢海川  阅读(42)  评论(0)    收藏  举报