浅谈对AOP的理解,简单易懂

一、pandas是什么?

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

下面先将怎么做,原理结合代码来讲,这样也比较好懂一点

二、使用步骤

在创建完普通的Maven项目以后,

1.导入依赖

向pom.xml中导入依赖,这一步没啥好说的,导入就完事了

<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配置文件

这一步有两种方法,这边我比较推荐第二种,我觉得这种方便很多,建一个普通的java类,然后加三个注解的事情

1.使用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/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>

2.使用配置类的方式

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步:添加一个业务类Service

这边就是简单地创建一个普通java类,然后写你自己的方法,记得加上那个@Service,就可以了

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步:添加一个切面类

这边主要注意这么一句话

* demo.MyService.*(..)

这句话是说对demo文档下的MyService下的所有的方法进行定位,然后我们看那个@Before,我们先定义好切点在哪里,在before切点,就可以在切点之前执行.这就是这个AOP最主要的东西了。这边总共有5个方法,具体的我都放置在第二个代码块.

@Before:通知方法会在目标方法调用之前执行
@After:通知方法会在目标方法返回或异常后调用
@AfterReturning:通知方法会在目标方法返回后调用
@AfterThrowing:通知方法会在目标方法抛出异常后调用
@Around:通知方法会将目标方法封装起来

/**
 * 切面类(增强类),对AccountService的方法进行增强
 */
@Component
@Aspect//表示这是一个切面类,增强类
public class MyAspect {
    //告诉程序,需要对那一个类的哪一个方法进行增强
    @Pointcut("execution(* demo.MyService.*(..))")
    public void pott(){}

    @Before("pott()")
    public void beforeEat(){
        System.out.println("大乱斗");
    }
}
@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();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42176665/article/details/128006114
今日推荐