0
点赞
收藏
分享

微信扫一扫

Spring AOP统一功能处理(切面、切点、连接点、通知)

西曲风 2023-01-19 阅读 161

目录

一、 AOP的一些前置知识

 1.1什么是Aop

1.2 AOP的作用 

1.3AOP基础组成 

 二、SpringAOP的实现

2.1添加SpringAOP框架支持

2.2定义切面(Aspect)

2.3定义切点(Pointcut)

2.4定义通知(Advice)

三、实例展示(计时器)

代码实现 


一、 AOP的一些前置知识

 1.1什么是Aop

Aop是一种统一处理某一问题的思想,比如验证用户是否登录

在为使用Aop的时候,我们需要验证的每个类(页面)都有调用验证方法,而使用了Aop后,我们只需要在某处把验证规则配置一下,就可以实现对需要验证的类的登录验证,不用每个类在重复调用验证方法了。

Aop由切面、切点、连接点、通知组成

而AOP是一种思想,而SpringAOP是这个框架对AOP思想的实现(类似IoC和DI) 

1.2 AOP的作用 

1.3AOP基础组成 

AOP由以下四部分组成:

AOP整个组成部分的概念如下图所示,以多个页面都要访问用户登录权限为例 

 


 二、SpringAOP的实现

2.1添加SpringAOP框架支持

在我们的项目的pom.xml中添加支持

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

 

2.2定义切面(Aspect)

 

 

2.3定义切点(Pointcut)

其中pointcut方法为空方法,其不需要方法体,此方法名就是起到一个“标识”的作用,标识下面的通知方法具体指的是哪个切点。

 

2.4定义通知(Advice)

切点和通知的关系

 

实现通知方法:在什么时机执行什么方法。
下面,我们以前置方法为例,演示一下。 

 


三、实例展示(计时器)

环绕通知使⽤@Around:通知包裹了被通知的⽅法,在被通知的⽅法通知之前和调⽤之后执⾏⾃定义的⾏为。

 

代码实现 

LoginAop代码 

package com.example.demo.aop;

import com.sun.corba.se.impl.ior.OldJIDLObjectKeyTemplate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

// 切面表示我们要统一出来的问题——比如验证用户是否登录(LoginAop类)
// 切点则是是否进行Aop拦截的规则(哪些页面不需要进行登录验证,哪些需要,这种规则)
// 连接点则是具体到哪些页面需要进行拦截(登录验证)
// 通知则是验证用户是否登录的那个具体方法实现(代码细节)——》前置通知,后置通知
// 验证当前是否登录 的aop实现类
@Component
@Aspect // 表示当前类是一个切面
public class LoginAop {
    // 定义切点
    @Pointcut("execution(* com.example.demo.controller.UserController.*(..))")
    public void pointcut() { // 标记切点
    }
    // 前置通知
    @Before("pointcut()") // 参数说明这个前置方法是针对与那个切点的
    public void doBefore() {
        System.out.println("前置通知");
    }
    // 后置通知
    @After("pointcut()")
    public void doAfter() {
        System.out.println("后置通知");
    }
    // 环绕通知
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        StopWatch stopWatch = new StopWatch();

        Object o =  null;
        System.out.println("环绕通知开始执行");
        try {
            stopWatch.start();
            o = joinPoint.proceed();
            stopWatch.stop();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("环绕通知结束执行");
        System.out.println("执行花费的时间: " + stopWatch.getTotalTimeMillis() + "ms");
        return o;
    }
}
举报

相关推荐

0 条评论