切面导向程序设计(Aspect-Oriented-Programming,AOP),它的目的在於将许多的共同方法抽离出来,与物件导向程序设计类似,但AOP 与OOP 不同的地方就在於,AOP 不用原方法呼叫共同方法,只需要指定执行共同方法的时机点即可。
AOP 相关注释都在Day 09 - Spring Boot 常用注释(下)有详细介绍,这边主要是展示JoinPoint 和ProceedingJoinPoint 的使用方法。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.example.iThomeIronMan.aop;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
// 将当前类别标示为Spring 容器管理的类别
@Component
@Aspect
public class LoginAspect {
private static final Logger logger = LoggerFactory.getLogger(LoginAspect.class);
// 设定切入点
@Pointcut("execution(* com.example.iThomeIronMan.controller..*(..))")
public void pointcut() {
}
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
System.out.println("=====Before advice starts=====");
logger.info("访问 " + joinPoint.getSignature().getName());
Arrays.stream(joinPoint.getArgs()).forEach(System.out::println);
System.out.println("=====Before advice ends=====");
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("=====Around advice starts=====");
long startTime = System.currentTimeMillis();
// 呼叫proceed() 方法开始执行原方法
Object result = joinPoint.proceed();
long spentTime = System.currentTimeMillis() - startTime;
logger.info("访问 " + joinPoint.getSignature().getName() + " Time spent: " + spentTime);
System.out.println("=====Around advice ends=====");
return result;
}
@After("pointcut()")
public void after(JoinPoint joinPoint) {
System.out.println("=====After advice starts=====");
logger.info("访问 /" + joinPoint.getSignature().getName());
Arrays.stream(joinPoint.getArgs()).forEach(System.out::println);
System.out.println("=====After advice ends=====");
}
}
AOP 观念与术语
【Spring Boot】第20课-切面导向程序设计(AOP)
<<: 【Day23】Git 版本控制 - 修改 commit 纪录:reset
>>: DAY 26 『 AVPlayerViewController - 播放影片 』
安装Unreal的过程意外频出啊,差点以为我的电脑出事了,结果是因为我time machine开着,...
Youtube连结:https://bit.ly/3mTlgpQ 软件世界中「树」长得跟现实生活中...
前言 以为很顺畅的,结果发现Python 3.9无法支援,那就只好用3.8罗!因为采了不小的雷,因此...
前言 今天我想来点轻松的议题,是一个大家在开发专案时都会遇到的状况。在开发时有时候资料夹结构会变得很...
在创造各式各样的物件时,有很多时候会发现怎麽重复的代码很多。 为了解决这个问题,可以采用继承与介面的...