spring(6)-AOP

1、理解

AOP(Aspect Oriented Programming):面向切面编程,面向方面编程。(AOP是一种编程技术)。
一些非业务逻辑比如日志、安全、事务等,统一叫作交叉业务.
其实就是将业务逻辑与交叉业务分开,可以让程序员专心的写业务逻辑。
用一句话总结AOP:将与核心业务无关的交叉业务代码独立的抽取出来,形成一个独立的组件,然后以横向交叉的方式应用到业务流程当中的过程被称为AOP。
AOP的优点:
● 第一:代码复用性增强。
● 第二:代码易维护。
● 第三:使开发者更关注业务逻辑。
在这里插入图片描述

2、AOP的七大术语

连接连JointPoint:其实是一个位置, 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后等位置。
切点 PointCut 在程序执行流程中,真正织入切面的方法。(一个切点对应多个连接点)
切面 Aspect: 切点 + 通知就是切面。
通知 Advice
○ 通知又叫增强,就是具体你要织入的代码。
○ 通知包括:
■ 前置通知
■ 后置通知
■ 环绕通知
■ 异常通知
■ 最终通知
织入 Weraving: 把通知应用到目标对象上的过程。
代理对象proxy: 一个目标对象被织入通知后产生的新对象。
目标对象Target:被织入通知的对象。
在这里插入图片描述

3、切点表达式

切点表达式用来定义通知(Advice)往哪些方法上切入。
切入点表达式语法格式:

execution([访问控制权限修饰符] 返回值类型 [全限定类名]方法名(形式参数列表) [异常])

访问控制权限修饰符:
● 可选项。
● 没写,就是4个权限都包括。
● 写public就表示只包括公开的方法。
返回值类型:
● 必填项。
● * 表示返回值类型任意。
全限定类名:
● 可选项。
● 两个点 “. .”代表当前包以及子包下的所有类。
● 省略时表示所有的类。
方法名:
● 必填项。
表示所有方法。
● set
表示所有的set方法。
形式参数列表:
● 必填项
● () 表示没有参数的方法
● (…) 参数类型和个数随意的方法
● () 只有一个参数的方法
● (
, String) 第一个参数类型随意,第二个参数是String的。
异常:
● 可选项。
● 省略时表示任意异常类型。
举例:
service包下所有的类中以delete开始的所有公开方法:
execution(public * com.powernode.mall.service. * .delete*(…))
mall包下所有的类的所有的方法
execution(* com.powernode.mall. .(. .))
所有类的所有方法
execution(
*(…))

4、使用spring的AOP

Spring对AOP的实现包括以下3种方式:
● 第一种方式:Spring框架结合AspectJ框架实现的AOP,基于注解方式。
● 第二种方式:Spring框架结合AspectJ框架实现的AOP,基于XML方式。
● 第三种方式:Spring框架自己实现的AOP,基于XML配置方式。
实际开发中,都是Spring+AspectJ来实现AOP。所以我们重点学习第一种和第二种方式。
什么是AspectJ?(Eclipse组织的一个支持AOP的框架。AspectJ框架是独立于Spring框架之外的一个框架,Spring框架用了AspectJ)。

4.1 准备工作

1、导入依赖

   <repositories>
    <!--Spring里程碑版本的仓库-->
    <repository>
        <id>repository.spring.milestone</id>
        <name>Spring Milestone Repository</name>
        <url>https://repo.spring.io/milestone</url>
    </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>6.1.0-M2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、在spring配置文件中 引入命名空间

<?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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.cky"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

<aop:aspectj-autoproxy proxy-target-class=“true”/> 开启自动代理之后,凡事带有@Aspect注解的bean都会生成代理对象。
proxy-target-class=“true” 表示采用cglib动态代理。
proxy-target-class=“false” 表示采用jdk动态代理。默认值是false。即使写成false,当没有接口的时候,也会自动选择cglib生成代理类。

4.2 基于AspectJ的AOP注解式开发

1、准备一个类

package com.cky.Service;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserService {
    public void insert(){
        System.out.println("订单生成....");
    }
}

2、定义切面类

package com.cky.Aspect;


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogAspect {

    @Before("execution(* com.cky.Service.*.*(..))")
    public void before(){
        System.out.println("通知前");
    }
}

3、添加注解,都添上组件,交给spring管理,之后切面类 要添上@Aspect注解,代表它是一个切面类。切面=切点+通知,在切面类里,我们可以定义通知,方法名随意,之后再方法上添加上注解,表示切点,即我们要切入哪个方法类的哪个方法上,使用切点表达式。
4、通知类型
通知类型包括:
● 前置通知:@Before 目标方法执行之前的通知
● 后置通知:@AfterReturning 目标方法执行之后的通知
● 环绕通知:@Around 目标方法之前添加通知,同时目标方法执行之后添加通知。
● 异常通知:@AfterThrowing 发生异常之后执行的通知
● 最终通知:@After 放在finally语句块中的通知

package com.cky.Aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component("logAspect")
@Aspect
public class LogAspect {
    @Pointcut("execution(* com.cky.Service.*.*(..))")
    public void qiedian(){

    }

    @Before("qiedian()")
    public void before(){
        System.out.println("前置通知");
    }

    @AfterReturning("qiedian()")
    public void afterReturning(){
        System.out.println("后置通知");
    }
    @After("qiedian()")
    public void after(){
        System.out.println("最终通知");
    }
    @Around("qiedian()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕前");
        proceedingJoinPoint.proceed();
        System.out.println("环绕后");
    }
    @AfterThrowing("qiedian()")
    public void afterThrowingAdvice(){
        System.out.println("异常通知");
    }

}

执行:

package com.cky.test;

import com.cky.Service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
    @Test
    public void test1(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.insert();
    }
}

在这里插入图片描述
环绕贯穿始终
模拟异常

package com.cky.Service;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserService {
    public void insert(){
        System.out.println("订单生成....");
        if (1==1){
            throw  new RuntimeException("模拟异常发生");
        }
    }
}

结果:
在这里插入图片描述
我们可以看出,发生异常后,后置通知和环绕通知的结束部分不会被执行,但是最终通知仍然会执行。
如果异常被捕捉到,那么通知仍然正常

package com.cky.Service;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserService {
    public void insert(){
        System.out.println("订单生成....");
        if (1==1){
            try {
                throw  new RuntimeException("模拟异常发生");
            }
            catch (Exception e){
                System.out.println(e);
            }

        }

    }
}

在这里插入图片描述

4.3 切面的先后顺序

在切点类上加上@Order(xxx)注解 比如Order(1) 这些 数值越低 优先级越高。

package com.cky.Aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component("logAspect")
@Aspect
@Order(2)
public class LogAspect {
    @Pointcut("execution(* com.cky.Service.*.*(..))")
    public void qiedian(){

    }

    @Before("qiedian()")
    public void before(){
        System.out.println("前置通知log");
    }

    @AfterReturning("qiedian()")
    public void afterReturning(){
        System.out.println("后置通知");
    }
    @After("qiedian()")
    public void after(){
        System.out.println("最终通知");
    }
    @Around("qiedian()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕前");
        proceedingJoinPoint.proceed();
        System.out.println("环绕后");
    }
    @AfterThrowing("qiedian()")
    public void afterThrowingAdvice(){
        System.out.println("异常通知");
    }

}

package com.cky.Aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class securityAspect {
    @Before("com.cky.Aspect.LogAspect.qiedian()")
    public void before(){
        System.out.println("前置通知security");
    }
}

结果:
在这里插入图片描述

4.4 全注解开发

代替xml的配置类

package com.cky.comfig;


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

@Configuration  //配置类
@ComponentScan({"com.cky"}) //组件扫描
@EnableAspectJAutoProxy() //自动代理开启
public class SpringConfig {
}

 @Test
    public void test1(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.insert();
    }

4.5 连接点

package com.cky.Aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class securityAspect {
    @Before("com.cky.Aspect.LogAspect.qiedian()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知security");
        System.out.println(joinPoint.getSignature()); //getSignature() 方法用于获取连接点处方法的签名信息
        //获取连接点处正在执行的方法的名称
        System.out.println(joinPoint.getSignature().getName());
        //获取声明连接点处正在执行的方法的类型的名称
        System.out.println(joinPoint.getSignature().getDeclaringTypeName());
        //获取声明连接点处正在执行的方法的类型的名称
        System.out.println(joinPoint.getSignature().getDeclaringType());
        //获取连接点处正在执行的方法的修饰符。这个方法返回一个整数,表示正在执行的方法的修饰符,通常使用 Java 的 java.lang.reflect.Modifier 类中的常量来解析这些修饰符。
        System.out.println(joinPoint.getSignature().getModifiers());
    }
}

4.6 多个切点对象

package com.cky.Aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class securityAspect {
    @Pointcut("execution(* com.cky.Service..delete*(..))")
    public void delete() {
    }
    @Pointcut("execution(* com.cky.Service..insert*(..))")
    public void insert() {
    }
    @Before("insert()||delete()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知security");
    }
}

相关推荐

  1. spring aop

    2024-04-03 16:56:02       39 阅读
  2. Spring AOP

    2024-04-03 16:56:02       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-03 16:56:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-03 16:56:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-03 16:56:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-03 16:56:02       20 阅读

热门阅读

  1. 顺序排序与蛮力法模式匹配算法

    2024-04-03 16:56:02       16 阅读
  2. A+B Problem

    2024-04-03 16:56:02       14 阅读
  3. OpenEuler虚拟机配置网络连接

    2024-04-03 16:56:02       19 阅读