阶段二-SpringAOP

为什么要使用AOP?

AOP是面向对象的补充,当我们需要为多个对象引入一个公共行为,比如日志,操作记录等,就需要在每个对象中引用公共行为,这样程序就产生了大量的重复代码,使用AOP可以完美解决这个问题。

AOP:全称是 Aspect Oriented Programming 即:面向切面编程。简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
Aop的作用:在程序运行期间,不修改源码对已有方法进行增强。
Aop优势:减少重复代码、提高开发效率、维护方便
AOP的实现方式:使用动态代理技术

一、通过注解使用AOP

1.1、需求定义

完成日志记录功能,当用户进行数据库增、删、改的时候记录操作日志。

1.2、需求分析

在系统调用Service中增、删、改的方法时通过AOP来记录操作日志

1.3、需求实现

第1步:添加坐标

<dependencies>
    <!--spring坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.9.RELEASE</version>
    </dependency>
    <!--解析切入点表达式-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.9.RELEASE</version>
    </dependency>
</dependencies>

第2步:在配置文件/配置类中开启生成切面的代理对象

使用配置文件的方式:添加配置beans.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"
       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/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 开启自动扫描注解-->
    <context:component-scan base-package="demo"/><!--开启AspectJ生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
使用配置类的方式
package demo;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration //设置为配置文件
@ComponentScan({"demo"}) //组件扫描
@EnableAspectJAutoProxy //开启生成切面的代理对象
public class SpringConfig {
}

第3步:添加一个业务类AccountService

package demo;import org.springframework.stereotype.Service;@Service
public class AccountService {public void saveAccount(){
//        int a = 10/0;
        System.out.println("执行了添加的操作");
    }public void deleteAccount(){
        System.out.println("执行了删除的操作");
    }public void updateAccount(){
        System.out.println("执行了修改的操作");
    }}

第4步:添加一个切面类

定义切入点表达式和通知类型

package demo;
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.*; 
import org.springframework.stereotype.Component;
@Component 
@Aspect //表示这是一个切面类 
public class Logger {
@Pointcut("execution(* demo.*.*(..))")//设置切入点表达式
private void pott(){}/**
 * 前置通知
 * 应用场景:权限控制(权限不足抛出异常)、记录方法调用信息日志
 */
@Before("pott()")
public void beforePrintLog(){
    System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志******");
}/**
 * 后置通知,在异常时不执行
 * 特点:在目标方法运行后返回值后再增强代码逻辑
 * 应用:与业务相关的,如银行在存取款结束后的发送短信消息
 */
@AfterReturning("pott()")
public void afterReturningPrintLog() {
    System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志=========");
}/**
 * 异常通知
 * 作用:目标代码出现异常,通知执行。记录异常日志、通知管理员(短信、邮件)
 * 应用场景:处理异常(一般不可预知),记录日志
 */
@AfterThrowing("pott()")
public void afterThrowingPrintLog() {
    System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志++++++++++++");
}/**
 * 最终通知,不管异常与否
 * 作用:不管目标方法是否发生异常,最终通知都会执行(类似于finally代码功能)
 * 应用场景:释放资源 (关闭文件、 关闭数据库连接、 网络连接、 释放内存对象 )
 */
@After("pott()")
public void afterPrintLog() {
    System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志&&&&&&&&&&&&&&&&&&");
}/**
 * 环绕通知
 * 特点:目标方法执行前后,都进行增强(控制目标方法执行)
 * 应用:日志、缓存、权限、性能监控、事务管理
 */
@Around("pott()")
public Object aroundPrintLog(ProceedingJoinPoint point){
    //定义返回值
    Object result = null;
    try {
        //获得切入点中方法的参数列表
        Object[] args = point.getArgs();
        //调用前置通知
        beforePrintLog();
        //执行切入点的方法
        result = point.proceed(args);
        //调用后置通知
        afterReturningPrintLog();
    } catch (Exception e){
        //调用异常通知
        afterThrowingPrintLog();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    return result;
}
}

第5步:定义测试类进行测试

package demo;

import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        //使用xml方式配置spring
//        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //使用配置类的方式配置spring
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = (AccountService) context.getBean("accountService");
        accountService.saveAccount();
//        accountService.deleteAccount();
//        accountService.updateAccount();
    }
}

运行效果请添加图片描述

1.5、知识点补充

1、切入点表达式的写法-execution函数

关键字:execution(表达式)
表达式:访问修饰符 返回值 包名.包名.包名...类名.方法名

在这里插入图片描述

2、Spring中的通知

Spring中一共有5种通知

前置通知(before)、后置通知(returning)、异常通知(throwing)、最终通知(after)、环绕通知(around)

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值