03【Spring AOP、CGBLIB代理】_aop切换到cglib代理时需要导包吗

03【Spring AOP、CGBLIB代理】

一、AOP前奏

1.1 案例

1.1.1 需求设计
  • 需求:设计一个用户类,提供增删改查功能,在每次增删改查前后都需要记录日志
package com.dfbz.dao;

import java.util.Date;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public class UserDao {

    public void save() {
        System.out.println("执行【save】操作 begin...,时间:【" + new Date() + "】");
        System.out.println("新增用户成功...");
        System.out.println("执行【save】操作 end...,时间:【" + new Date() + "】");
    }

    public void delete() {
        System.out.println("执行【delete】操作 begin...,时间:【" + new Date() + "】");
        System.out.println("删除用户成功...");
        System.out.println("执行【delete】操作 end...,时间:【" + new Date() + "】");
    }

    public void update() {
        System.out.println("执行【update】操作 begin...,时间:【" + new Date() + "】");
        System.out.println("修改用户成功...");
        System.out.println("执行【update】操作 end...,时间:【" + new Date() + "】");
    }

    public void query() {
        System.out.println("执行【query】操作 begin...,时间:【" + new Date() + "】");
        System.out.println("查询用户成功...");
        System.out.println("执行【query】操作 end...,时间:【" + new Date() + "】");
    }
}

  • 执行测试:
package com.dfbz.test;

import com.dfbz.dao.UserDao;
import org.junit.Test;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public class Demo01 {

    @Test
    public void test1() {
        UserDao userDao=new UserDao();
        userDao.save();
    }
}

执行效果:

在这里插入图片描述

1.1.2 需求修改

需求修改如下:修改日志时间格式为yyyy-MM-dd hh:mm:ss

  • UserDao:
package com.dfbz.dao;

import java.text.SimpleDateFormat;
import java.util.Date;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public class UserDao {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    public void save() {
        System.out.println("执行【save】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("新增用户成功...");
        System.out.println("执行【save】操作 end...,时间:【" + sdf.format(new Date()) + "】");
    }

    public void delete() {
        System.out.println("执行【delete】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("删除用户成功...");
        System.out.println("执行【delete】操作 end...,时间:【" + sdf.format(new Date()) + "】");
    }

    public void update() {
        System.out.println("执行【update】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("修改用户成功...");
        System.out.println("执行【update】操作 end...,时间:【" + sdf.format(new Date()) + "】");
    }

    public void query() {
        System.out.println("执行【query】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("查询用户成功...");
        System.out.println("执行【query】操作 end...,时间:【" + sdf.format(new Date()) + "】");
    }
}

执行测试类:

在这里插入图片描述

1.1.3 需求增加

需求增加:在查询操作执行之后存入缓存,增、删、改操作时清除缓存;

  • UserDao:
package com.dfbz.dao;

import java.text.SimpleDateFormat;
import java.util.Date;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public class UserDao {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    public void save() {
        System.out.println("执行【save】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("新增用户成功...");
        System.out.println("执行【save】操作 end...,时间:【" + sdf.format(new Date()) + "】");

        System.out.println("清除缓存成功...");
    }

    public void delete() {
        System.out.println("执行【delete】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("删除用户成功...");
        System.out.println("执行【delete】操作 end...,时间:【" + sdf.format(new Date()) + "】");

        System.out.println("清除缓存成功...");
    }

    public void update() {
        System.out.println("执行【update】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("修改用户成功...");
        System.out.println("执行【update】操作 end...,时间:【" + sdf.format(new Date()) + "】");

        System.out.println("清除缓存成功...");
    }

    public void query() {
        System.out.println("执行【query】操作 begin...,时间:【" + sdf.format(new Date()) + "】");
        System.out.println("查询用户成功...");
        System.out.println("执行【query】操作 end...,时间:【" + sdf.format(new Date()) + "】");

        System.out.println("存入缓存成功...");
    }
}

执行测试类:

在这里插入图片描述

1.1.4 分析存在的问题
  • 职责不明确:我们仔细观察会发现,我们的某个方法执行的功能非常多(耦合性高,内聚性低),不相关的功能也存在方法中,甚至不相关的功能代码多余核心代码;

在这里插入图片描述

  • 代码非常冗余:以日志需求为例,只是为了满足这个单一需求,就不得不在多个模块(方法)里多次重复相同的日志代码。如果日志需求发生变化,必须修改所有模块。

在这里插入图片描述

1.2 动态代理

针对上面的问题,我们可以使用之前学过的动态代理来解决这个问题;

1.2.1 定义接口:
  • UserDaoInterface:
package com.dfbz.dao;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public interface UserDaoInterface {

    // 新增
    void save();

    // 删除
    void delete();

    // 修改
    void update();

    // 查询
    void query();
}

UserDao实现UserDaoInterface接口:

在这里插入图片描述

1.2.2 日志代理类
  • LoggerHandler:
package handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro: 日志处理器,执行增删改查操作时记录日志
 \*/
public class LoggerHandler implements InvocationHandler {


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    // 目标对象
    private Object target;

    public LoggerHandler (Object target){
        this.target=target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("执行【" + method.getName() + "】操作 begin...,时间:【" + sdf.format(new Date()) + "】");

        // 执行目标方法并获取目标方法的返回值
        Object returnVal = method.invoke(target, args);

        System.out.println("执行【" + method.getName() + "】操作 end...,时间:【" + sdf.format(new Date()) + "】");
        return returnVal;
    }
}

1.2.3 缓存代理类:
package handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro: 缓存处理器: 当执行query方法时存入缓存;执行save/update/delete方法时清除缓存;
 \*/
public class CacheHandler implements InvocationHandler {


    // 目标对象
    private Object target;

    public CacheHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 执行目标方法并获取目标方法的返回值
        Object returnVal = method.invoke(target, args);

        // 获取要执行的方法名称
        String methodName = method.getName();
        if (
                "save".equals(methodName) ||
                        "update".equals(methodName) ||
                        "delete".equals(methodName)

        ) {
            System.out.println("清除缓存成功...");
        } else if ("query".equals(methodName)) {
            System.out.println("存入缓存成功...");
        }

        return returnVal;
    }
}

1.2.4 测试类
@Test
public void test2() {

    // 针对日志功能的增强(具备日志功能)
    UserDaoInterface userDaoLoggerProxy = (UserDaoInterface) Proxy.newProxyInstance(
            Demo01.class.getClassLoader(),
            UserDao.class.getInterfaces(),
            new LoggerHandler(new UserDao())
    );

    // 具备日志功能,不具备缓存功能
    userDaoLoggerProxy.query();

    System.out.println("-----------------");
    // 针对缓存功能的增强
    UserDaoInterface userDaoCacheProxy = (UserDaoInterface) Proxy.newProxyInstance(
            Demo01.class.getClassLoader(),
            UserDao.class.getInterfaces(),
            new CacheHandler(userDaoLoggerProxy)        // 传入已经进行日志增强的代理类,继续代理加强缓存相关功能
    );

    // 具备日志和缓存功能
    userDaoCacheProxy.query();
}

执行效果:

在这里插入图片描述

二、AOP

2.1 AOP 概述

AOP(Aspect Oriented Programming),即面向切面编程。通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件系统开发中的一个热点,也是Spring框架的一个重点。利用AOP可以实现业务逻辑各个部分的隔离,从而使得业务逻辑各个部分的耦合性降低,提高程序的可重用性,同时提高开发效率。

2.1.1 纵向编程

在这里插入图片描述

2.1.2 纵横配合的编程

面向切面的意思简单来说就是:纵向重复,横向抽取,在我们的业务中间切一刀来填充我们的增强代码;

在这里插入图片描述

AOP编程操作的主要对象是切面(aspect),而切面模块化横切关注点(需要增强的方法)。

2.2 AOP相关语术

2.2.1 Joinpoint(连接点):
  • 连接点:在程序执行过程中,需要拦截的方法;
  • 根据规则,可以指定拦截的方法,我们将每一个被拦截的方法称为连接点。如:UserService中的save()方法就是连接点
2.2.2 Pointc

必看视频!获取2024年最新Java开发全套学习资料 备注Java

ut(切入点):

  • 切入点:就是拦截方法设置的规则,连接点的一系列集合
  • 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义,比如我们刚刚的的案例中,save/delete/update/query这些都是我们需要增强的方法,这些方法也是我们刚刚说的连接点,我们需要通过一个表达式把这些需要增强的方法找出来,通过这个表达式查找出来的一批方法就称为切入点;
2.2.3 Advice(通知):
  • 通知:增强连接点的实现代码(就是需要为连接点绑定的方法)
  • 所谓通知是指拦截到Joinpoint之后所要做的事情(增强的代码)就是通知

由于执行代码的时机不同,比如我们刚刚的日志增强代码在执行目标对象方法前后都需要执行,缓存代码则是在执行目标对象之后才执行。因此通知也被化分为了很多种类型:

  • 前置通知(Before):执行连接点方法之前执行
  • 环绕通知(Around):环绕连接点方法执行
  • 后置通知(After):执行连接点方法之后执行
  • 返回通知(After Running):在连接点方法返回结果之后执行,如果方法出现异常则不会执行此通知(通常是最后执行)
  • 异常通知(After Throwing):在连接点方法抛出异常之后执行
2.2.4 target(目标对象):
  • 目标对象:被代理对象,连接点的所属方法,也就是需要增强的方法
2.2.5 Weaving(织入):
  • 织入:与前面的语术不一样,织入是个动词,指的是将通知(增强的代码)应用到切入点(需要增强的方法)形成切面的过程,在具体应用中作用不大,我们了解即可;
2.2.6 Proxy(代理):
  • 代理:一个类被AOP织入增强后,就产生一个结果代理类
2.2.7 Aspect(切面):
  • 切面:我们的拦截处理类;由于处理类里面需要执行所有拦截到的目标方法,也就是切入点,还包括我们增强的功能代码,也就是通知,因此我们一般称切面(Aspect)=切入点(Pointcut)+通知(Advice)

三、Spring中的AOP

3.1 AspectJ

AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,是Java社区中最完整最流行的AOP框架

在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置的AOP。

Tips:我们本次课程并不是使用原生的AspectJ,而是使用Spring对AspectJ的封装

3.2 切入点表达式

切入点就是能够增强的方法的一系列集合,我们要通过表达式的方式定位一个或多个具体的连接点,这些所有的连接点被称为切入点;

  • 语法:
execution( [权限修饰符] [返回值类型] [简单类名/全类名] [方法名] ([参数列表]) )

示例一:

execution(\* com.dfbz.dao.UserDao.*(..))
    
说明: com.dfbz.dao包下的UserDao接口中声明的所有方法

// 解释:任意权限修饰符、任意方法返回值、com.dfbz.dao.UserDao接口、任意方法名、任意参数列表
    
第一个"\*"代表任意修饰符及任意返回值。
第二个"\*"代表任意方法。
".."匹配任意数量、任意类型的参数。
若目标类、接口与该切面类在同一个包中可以省略包名。

示例二:

execution(public \* UserDao.*(..))
    
说明: UserDao接口的所有公有方法 

// 必须public修饰、任意返回值、UserDao接口、任意方法名、任意参数列表

示例三:

execution(public String UserDao.*(..))
    
说明: UserDao中所有返回值为String类型的共有方法方法

// 必须public修饰、方法返回值必须String、UserDao接口(一级目录)、任意方法名、任意参数列表

示例四:

execution(private \* UserDao.*(Integer, ..))
    
说明: 第一个参数为Integer类型的private修饰的方法。
    
// 必须是private修饰、任意方法返回值、UserDao接口(一级目录)、任意方法名、第一个参数必须是Integer,后面可以匹配任意参数(包含0个)
".." 匹配任意数量、任意类型的参数。

示例五:

execution(public double UserDao.*(double, double))
    
说明: 修饰符为public,返回值为double,UserDao中的两个参数都为double的方法
// 必须是public修饰符、返回值类型是double、UserDao接口(一级目录)、任意方法名、第一个参数为double、第二个参数为double

示例六:

execution(public void \*.UserDao.*(..))
    
说明: 修饰符为public,返回值为void,任意一级包下的UserDao的任意方法
// 必须是public修饰符、返回值为void、任意一级包下的UserDao的任意方法、任意方法名、任意参数列表
注意:是任意一级包下的UserDao类,如果是多级包则不行,如:com.dfbz.dao.UserDao,必须写成public void \*.*.*.UserDao.*(..)

示例七:

execution (\* \*.save(User,..)) || execution(\* \*.delete(Integer,..))

说明: 
	任意修饰符和返回值,任意包下的任意类,第一个参数为User的save方法
    或者
    任意修饰符和返回值,任意包下的任意类,第一个参数为Integer的delete方法

Tips:当权限修饰符设置为*时,方法的返回值也必须为*,而且不必使用*显示的写出

例如这样就是一种错误的写法:execution(* String UserDao.*(..))execution(* * UserDao.*(..))

可以这样:execution(* UserDao.*(..))

3.3 基于XML配置AOP

3.1.1 搭建环境
  • Maven依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dfbz</groupId>
    <artifactId>01_Spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--spring环境依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <!--spring整合aspectj的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <!--spring整合Junit的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3.1.2 目标对象
package com.dfbz.dao;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
public class UserDao {

    public void save() {
        System.out.println("新增用户成功...");
    }

    public void delete(Integer id) {
        System.out.println("删除用户【" + id + "】成功...");
    }

    public void update() {
        System.out.println("修改用户成功...");
    }

    public String query() {
        System.out.println("查询用户成功...");
        return "success";
    }
}

3.1.3 切面类
package com.dfbz.aspect;

import org.aspectj.lang.ProceedingJoinPoint;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro: 针对UserDao进行增强的切面类
 \*/
public class MyAspect {

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

    public Object around(ProceedingJoinPoint around) throws Throwable {         //环绕通知

        System.out.println("环绕通知之前...");
        
        // 执行下一个切面的通知,如果没有下一个切面那么执行目标方法
        Object proceed = around.proceed();          
        
        System.out.println("环绕通知之后...");
        return proceed;                             //将目标方法的返回值返回
    }
    
    public void after(){
        System.out.println("后置通知...");
    }

    public void afterReturning(){
        System.out.println("返回通知...");
    }

    public void afterThrowing(){
        System.out.println("异常通知...");
    }
}

3.1.4 Spring配置

切面相关配置:

  • <aop:aspectj-autoproxy />:开启AOP代理,当Spring IOC容器侦测到bean配置文件中的<aop:aspectj-autoproxy>元素时,会自动为与AspectJ切面匹配的bean创建代理

  • <aop:config>:aop核心配置,在此标签内配置切点、切面等

    • <aop:pointcut>:配置切入点
    • <aop:aspect ref="myAspect">:配置切面,并指定切面
      • <aop:before method="" pointcut-ref="">:前置通知,指定前置通知方法和采用哪个切点
      • <aop:around method="" pointcut-ref="">:环绕通知
      • <aop:after method="" pointcut-ref="">:后置通知
      • <aop:after-returning method="" pointcut-ref="">:后置返回通知
      • <aop:after-throwing method="" pointcut-ref="">:异常通知
  • spring.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">


    <bean class="com.dfbz.dao.UserDao"></bean>

    <!--
 开启AOP自动代理
 proxy-target-class: 是否采用GBLIB代理
 true: 采用CGlib代理
 false: 采用JDK动态代理(必须要有接口的时候才可以选择为false,如果没有接口会默认采用GBLIB)
 -->
    <aop:aspectj-autoproxy />

    <!--配置切面类-->
    <bean id="myAspect" class="com.dfbz.aspect.MyAspect"></bean>

    <!--aop核心配置-->
    <aop:config>
        <!--
 配置切点
 id:切点名称
 expression:切点表达式
 -->
        <aop:pointcut id="myPoint" expression="execution(public void com.dfbz.dao.UserDao.save(..))"/>

        <!--
 配置切面
 before:前置通知
 after-returning:返回通知
 around:环绕通知
 after:后置通知
 after-throwing:异常通知
 -->
        <aop:aspect ref="myAspect">
            <!--【前置通知】-->
            <aop:before method="before" pointcut-ref="myPoint"/>
            <!--【环绕通知】-->
            <aop:around method="around" pointcut-ref="myPoint"/>
            <!--【返回通知】-->
            <aop:after-returning method="afterReturning" pointcut-ref="myPoint"/>
            <!--【后置通知】-->
            <aop:after method="after" pointcut-ref="myPoint"/>
            <!--【异常通知】-->
            <aop:after-throwing method="afterThrowing" pointcut-ref="myPoint"/>
        </aop:aspect>
    </aop:config>
</beans>

  • 测试代码:
package com.dfbz.demo;

import com.dfbz.dao.UserDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class Demo01 {

    @Autowired
    private UserDao userDao;

    @Test
    public void test1()throws Exception{
        userDao.save();
    }
}

执行效果:

在这里插入图片描述

执行目标方法出现异常的执行情况:

在这里插入图片描述

3.1.5 通知执行顺序

关于通知的执行顺序,每个版本都有很大的改动,并且配置顺序不一样也会导致通知执行顺序不一致,再者注解方式和配置文件方式的执行运行也会有些不同,因此我们不需要死记各个通知的执行顺序;通常情况下,通知执行的顺序是:

  • 正常情况:前置通知—>环绕通知—>目标方法—>环绕通知—>返回通知—>后置通知
  • 出现异常情况:前置通知—>环绕通知—>目标方法—>环绕通知—>后置通知—>异常通知

在这里插入图片描述

但是如果更改了切面中配置通知的顺序,则执行的顺序会有所改变,并且没有什么规律;我们一般不用太在意通知的执行顺序,因为前置通知和后置通知一定在目标方法执行前后;

Tips:当执行目标方法出现异常时,不会有目标对象不会有返回值,因此返回通知不会被执行;

3.1.6 AOP相关API
1)ProceedingJoinPoint类

ProceedingJoinPoint类是AOP编程中用于获取目标对象/方法信息的一个类;提供的方法如下:

  • getStaticPart():获取切入点表达式
  • getTarget():获取目标对象
  • getThis():获取当前对象(代理对象)
  • getArgs():获取代理对象在调用方法时传递的参数
  • getSignature():获取签名
  • proceed():执行目标方法

2)Signature类

Signature主要是描述目标对象的类;其提供的常用方法如下:

  • getDeclaringType():获取目标对象
  • getDeclaringTypeName():获取目标对象全类名
  • getName():获取目标方法名称

测试代码:

public Object around(ProceedingJoinPoint joinPoint) throws Throwable {           // 需要执行目标方法

    // 切入点表达式(execution(void com.dfbz.dao.UserDao.query()))
    System.out.println(joinPoint.getStaticPart());

    // 目标对象(class com.dfbz.dao.UserDao)
    System.out.println(joinPoint.getTarget().getClass());

    // 获取到代理对象(class com.dfbz.dao.UserDao$$EnhancerBySpringCGLIB$$4354d856)
    System.out.println(joinPoint.getThis().getClass());

    // 代理对象在调用方法时传递的参数
    System.out.println(Arrays.toString(joinPoint.getArgs()));

    System.out.println("----------------------");


    // 获取方法签名
    Signature signature = joinPoint.getSignature();

    // 获取目标对象(class com.dfbz.dao.UserDao)
    System.out.println(signature.getDeclaringType());

    // 获取目标对象全类名(com.dfbz.dao.UserDao)
    System.out.println(signature.getDeclaringTypeName());

    // 获取执行目标方法的名称(query)
    System.out.println(signature.getName());                       

    // 执行下一个切面的通知,如果没有下一个切面那么执行目标方法,并获取目标方法的返回值
    Object result = joinPoint.proceed();

    // 将目标方法的返回值原封不动的返回了给了方法的调用者
    return result;
}

执行结果如下:

在这里插入图片描述

3.4 使用注解配置切面

1)xml和注解搭配使用
  • spring.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 https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--包扫描-->
    <context:component-scan base-package="com.dfbz" />

    <!-- 开启AOP自动代理 -->
    <aop:aspectj-autoproxy />

</beans>

  • 切面类:
package com.dfbz.aspect;

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

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro: 针对UserDao进行增强的切面类
 \*/
@Aspect     // 标注这是一个配置类
@Component    // 交给IOC管理
public class MyAspect {

    // 定义切点
    @Pointcut("execution(\* com.dfbz.dao.UserDao.save())")
    public void pt(){}

    // @Before("execution(\* com.dfbz.dao.UserDao.\*())") // 单独定义切点
    @Before("pt()")                     // 引用定义的切点
    public void before(){
        System.out.println("前置通知...");
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint around) throws Throwable {         //环绕通知

        System.out.println("环绕通知之前...");
        Object proceed = around.proceed();          //执行目标方法
        System.out.println("环绕通知之后...");
        return proceed;                             //将目标方法的返回值返回
    }

    @After("pt()")
    public void after(){
        System.out.println("后置通知...");
    }

    @AfterReturning("pt()")
    public void afterReturning(){
        System.out.println("返回通知...");
    }

    @AfterThrowing("pt()")
    public void afterThrowing(){
        System.out.println("异常通知...");
    }
}

在注解情况下,通知的顺序如下:

在这里插入图片描述

Tips:在注解配置情况下,执行完后置通知又回到环绕通知了;所以环绕通知中我们一般不执行代码,只执行目标对象的方法;

2)纯注解配置

分析:主要就是<aop:aspectj-autoproxy />改为注解配置

配置类:

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
@ContextConfiguration
@ComponentScan("com.dfbz")
@EnableAspectJAutoProxy         // 开启AOP自动代理(是否启用CGLIB代理)
public class SpringConfig {
    
    
}

3.5 多切面配置

多个切面执行顺序可以由@Order()注解来配置,数字越小,越先执行,多个切面执行顺序如下:

在这里插入图片描述

  • 定义切面1:
package com.dfbz.aspect;

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

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
@Aspect
@Component
@Order(1)           // 切面执行顺序,数字越小优先级越高
public class MyAspect\_01 {

    // 定义切点
    @Pointcut("execution(\* com.dfbz.dao.UserDao.save())")
    public void pt() {
    }

    @Before("pt()")
    public void before() {
        System.out.println("【MyAspect\_01】前置通知...");
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint around) throws Throwable {
        Object proceed = around.proceed();
        return proceed;
    }

    @After("pt()")
    public void after() {
        System.out.println("【MyAspect\_01】后置通知...");
    }

    @AfterReturning("pt()")
    public void afterReturning() {
        System.out.println("【MyAspect\_01】返回通知...");
    }

    @AfterThrowing("pt()")
    public void afterThrowing() {
        System.out.println("【MyAspect\_01】异常通知...");
    }
}



## 总结

这个月马上就又要过去了,还在找工作的小伙伴要做好准备了,小编整理了大厂java程序员面试涉及到的绝大部分**面试题及答案**,希望能帮助到大家

![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/c7565d9920bae3306b2df55a18293047.webp?x-oss-process=image/format,png)

![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/3cd2c2a494d94d4f01473d44ef9a70b4.webp?x-oss-process=image/format,png)

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

/\*\*
 \* @author lscl
 \* @version 1.0
 \* @intro:
 \*/
@Aspect
@Component
@Order(1)           // 切面执行顺序,数字越小优先级越高
public class MyAspect\_01 {

    // 定义切点
    @Pointcut("execution(\* com.dfbz.dao.UserDao.save())")
    public void pt() {
    }

    @Before("pt()")
    public void before() {
        System.out.println("【MyAspect\_01】前置通知...");
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint around) throws Throwable {
        Object proceed = around.proceed();
        return proceed;
    }

    @After("pt()")
    public void after() {
        System.out.println("【MyAspect\_01】后置通知...");
    }

    @AfterReturning("pt()")
    public void afterReturning() {
        System.out.println("【MyAspect\_01】返回通知...");
    }

    @AfterThrowing("pt()")
    public void afterThrowing() {
        System.out.println("【MyAspect\_01】异常通知...");
    }
}



## 总结

这个月马上就又要过去了,还在找工作的小伙伴要做好准备了,小编整理了大厂java程序员面试涉及到的绝大部分**面试题及答案**,希望能帮助到大家

[外链图片转存中...(img-YpNFBwpZ-1716377102762)]

[外链图片转存中...(img-PkzAoPUX-1716377102763)]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值