spring AOP基本概念及使用

1.基本概念

AOP(Aspect-Oriented Programming,面向切面编程),它提供了一种编程范式,用于将那些与业务逻辑无关的行为(如日志、权限、事务管理等)封装到可重用的模块中。即松耦合,将公共动作抽离、聚集起来,在不动业务代码的情况下,加入额外的公共逻辑。提前声明,本文描述的都是基于java动态代理的AOP。

1.1 Spring AOP的编程术语

  • 切面(Aspect):定义通知(Advice)和切点(PointCut)的地方。

  • 通知(Advice):又名"增强",定义了切面要完成的工作 以及何时执行 这个工作。即你要添加的公共逻辑

    • 官方原文:action to take at a joinpoint(作用在连接点上的动作)
  • 切点(PointCut):定义通知(Advice)作用于那些连接点

    • 官方原文:A pointcut is composed of a {@link ClassFilter} and a {@link MethodMatcher}(一个pointcut是由ClassFilter和MethodMatcher组成)
  • 连接点(Jointpoint):应用执行过程中能够插入切面的一个点,它可以是一个方法、构造函数、一个字段。即通知(Advice)要作用、影响的地方。在spring中仅支持method

    • 官方原文:a runtime joinpoint is then the reification of an access to an accessible object (a method, a constructor, a field)
  • 引入(Introduction):引入允许我们向现有的类添加新的方法或属性

  • 前4个概念比较重要,平时用到的多,用图表示他们的关系:

1.2 通知(advice)的类型

类型 释义
Around 环绕通知
Before 前置通知
AfterReturning 后置通知
AfterThrowing 异常通知
After 最终通知

用图表示"通知"的类型: ps:同时声明5个类型的Advice,他们的执行顺序也是这样的。

1.3 切点表达式

spring支持AspectJ的切点表达式,execution表达式语法。

sql 复制代码
execution(<modifiers-pattern?> <ret-type-pattern> <declaring-type-pattern?><name-pattern>(<param-pattern>) <throws-pattern?>)

execution(<修饰符?> <返回值> <类路径?> <方法名>(<参数类型>) <异常类型?>)

带?的可以省略

这个方面资料看的不多,可以自行度娘、AI,基础使用很简单。

2. 使用

声明接口

java 复制代码
public interface UserService {  
    String myName(String name);  
}

声明实现类

java 复制代码
@Service  
public class UserServiceImpl implements UserService {  
    @Override  
    public String myName(String name) {  
        System.out.println("i'm" + name);  
        return name;  
    }  
}

声明切面

java 复制代码
@Configuration  
@EnableAspectJAutoProxy  
@Aspect  
public class AspectDemo {  
    //环绕通知  
    @Around(value = "execution(* com.dy..*.*(..))")  
    public Object aopAround(ProceedingJoinPoint point) throws Throwable {  
        System.out.println("Around advice before method execute !!!");  
        try {  
            return point.proceed();  
        } finally {  
            System.out.println("Around advice after method execute !!!");  
        }  
    }  
  
    // 前置通知  
    @Before(value = "execution(* com.dy..*.*(..))")  
    public void aopBefore() {  
        System.out.println("before advice method execute !!!");  
    }  
  
    // 最终通知  
    @After(value = "execution(* com.dy..*.*(..))")  
    public void aopAfter() {  
        System.out.println("after advice method execute !!!");  
    }  
  
    // 后置通知  
    @AfterReturning(value = "execution(* com.dy..*.*(..))")  
    public void aopAfterReturn() {  
        System.out.println("afterReturn advice method execute !!!");  
    }  
  
    // 异常通知  
    @AfterThrowing(value = "execution(* com.dy..*.*(..))")  
    public void aopAfterThrowing() {  
        System.out.println("afterThrow advice method execute !!!");  
    }  
}

运行

java 复制代码
@SpringBootApplication  
public class App {  
    public static void main(String[] args) {  
        ConfigurableApplicationContext context = SpringApplication.run(App.class);  
        UserService userService =(UserService)context.getBeanFactory().getBean("userServiceImpl");  
        userService.myName("hh");  
    }  
}

运行结果

java 复制代码
Around advice before method execute !!!  // 环绕通知
before advice method execute !!! // 前置通知
hello,i'm hh // 执行真实方法
after return advice method execute !!!  // 后置通知
after advice method execute !!!  // 最终通知
Around advice after method execute !!! // 环绕通知

3. 总结

AOP的使用很简单,理解"基本概念"后,使用基本不成问题。第一次接触的小伙伴,可以先略读概念,学会使用后,再回顾精读、理解概念,效果更佳。

相关推荐
J_bean3 小时前
Spring AI Alibaba 项目接入兼容 OpenAI API 的大模型
人工智能·spring·大模型·openai·spring ai·ai alibaba
柳贯一(逆流河版)5 小时前
Spring 三级缓存:破解循环依赖的底层密码
java·spring·缓存·bean的循环依赖
蚰蜒螟9 小时前
Spring 和 Lettuce 源码分析 Redis 节点状态检查与失败重连的工作原理
java·redis·spring
duration~9 小时前
SpringAI集成MCP
人工智能·后端·spring·ai
悟纤9 小时前
Spring Boot 实用小技巧:多级缓存(Caffeine + Redis)- 第545篇
spring boot·后端·spring
励志成为糕手9 小时前
企业级Spring事务管理:从单体应用到微服务分布式事务完整方案
分布式·spring·微服务·隔离级别·事务管理
Dajiaonew16 小时前
Spring AI RAG 检索增强 应用
java·人工智能·spring·ai·langchain
Java小白程序员1 天前
Spring Framework :IoC 容器的原理与实践
java·后端·spring
小李是个程序1 天前
登录与登录校验:Web安全核心解析
java·spring·web安全·jwt·cookie
ciku1 天前
Spring AI 集成阿里云百炼平台
人工智能·spring·阿里云