如何通过Spring使用面向切面编程(AOP)

前言

这里将演示如何通过Spring使用面向切面编程(AOP),也就是说不修改service层的源代码对其中的方法进行增强,我会模拟添加一个日志功能进行演示。

使用步骤

1.创建maven工程

用idea创建很简单就不赘述了
在这里插入图片描述

2.导包

打开pom.xml,导入这两个包

<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.8.7</version>
 </dependency>

导入之后是这样的
在这里插入图片描述

3.导入约束,编写配置文件(到这一步环境就配置完了)

在resource文件下新建bean.xml(名字可以自定义,这里我用bean)

<?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>

如下
在这里插入图片描述

4.开始使用(用声明的方式完成)

这里以加日志功能为例子演示如何以声明的方式通过Spring使用面向切面编程

1.创建文件夹

在这里插入图片描述

2.在service层编写AccountService接口及其实现类AccountServiceImpl

在这里插入图片描述

AccountService接口代码

public interface AccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();
    /**
     * 模拟更新账户
     * @param i
     */
    void updateAccount(int i);
    /**
     * 模拟删除账户
     */
    void  deleteAccount();
}

实现类AccountServiceImpl代码

public class AccountServiceImpl implements AccountService {
    public void saveAccount() {
        System.out.println("执行了保存");
    }
    public void updateAccount(int i) {
        System.out.println("执行了更新"+i);
    }
    public void deleteAccount() {
        System.out.println("执行了删除");
    }
}

3.在utils层编写日志类Logger

这里只是简单演示一下的日志

public class Logger {
    /** 前置通知*/
    public  void beforePrintLog(){
        System.out.println("前置通知开始记录日志了");
    }
    /**后置通知*/
    public  void afterReturningPrintLog(){
        System.out.println("后置通知开始记录日志了");
    }
    /**异常通知*/
    public  void afterThrowingPrintLog(){
        System.out.println("异常通知开始记录日志了");
    }
    /**最终通知*/
    public  void afterPrintLog(){
        System.out.println("最终通知开始记录日志了");
    }
    /**环绕通知*/
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            //获取参数
            Object[] args = pjp.getArgs();
            System.out.println("前置通知");
            rtValue = pjp.proceed(args);//明确切入点
            System.out.println("后置通知");
            return rtValue;
        }catch (Throwable t){
            System.out.println("异常通知");
            throw new RuntimeException(t);
        }finally {
            System.out.println("最终通知");
        }
    }
}

在这里插入图片描述

4.在配置文件注入Logger类和实现类AccountServiceImpl并配置AOP

 <!-- 配置srping的Ioc,把service对象配置进来-->
    <bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>
    <!-- 配置Logger类 -->
    <bean id="logger" class="com.utils.Logger"></bean>
    <!--配置AOP-->
    <aop:config>
        <!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
              此标签写在aop:aspect标签内部只能当前切面使用。
              它还可以写在aop:aspect外面,此时就变成了所有切面可用
          -->
        <aop:pointcut id="pt1" expression="execution(* com.service.impl.*.*(..))"></aop:pointcut>
        <!--配置切面 -->
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知的类型,并且建立通知方法和切入点方法的关联-->
            <!-- 配置前置通知:在切入点方法执行之前执行
            <aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>
            <!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个
            <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>-->
            <!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>-->
            <!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行
            <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>-->
            <!-- 配置环绕通知 用起来比较特殊需要到切入点方法的参数中,加入proceed(),此方法就相当于明确调用切入点方法-->
            <aop:around method="aroundPringLog" pointcut-ref="pt1"/>
        </aop:aspect>
    </aop:config>

在这里插入图片描述

5.编写测试类进行测试

在这里插入图片描述

public class AOPTest {

    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        AccountService as = (AccountService)ac.getBean("accountService");
        //3.执行方法
        as.saveAccount();
        as.updateAccount(1);
        as.deleteAccount();
    }
}

前置通知、后置通知、最终通知、异常通知、环绕通知的配置都配置好了自行解开注释就行了(4-4)、这里就只测试前置通知

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值