0

0

揭示 Spring AOP 的内部工作原理

WBOY

WBOY

发布时间:2024-09-07 10:36:16

|

862人浏览过

|

来源于dev.to

转载

揭示 spring aop 的内部工作原理

在这篇文章中,我们将揭秘 spring 中面向方面编程 (aop) 的内部机制。重点将放在理解 aop 如何实现日志记录等功能,这些功能通常被认为是一种“魔法”。通过浏览核心 java 实现,我们将了解 java 的反射、代理模式和注释,而不是任何真正神奇的东西。

先决条件

  • java 核心代理 api
  • 反射api
  • 注释api

这些都是 java.lang.reflect、java.lang.annotation 和 javassist.util.proxy 包的一部分。

核心机制

spring aop 的核心是代理对象、方法拦截器和反射的概念。此模式中的关键角色是 methodhandler(或调用处理程序)。该处理程序通过拦截方法调用来控制代理对象的行为。当在代理上调用方法时,它会通过处理程序传递,其中可以通过反射对注释进行内省。根据应用的注释,可以在异常之前、之后或异常时执行必要的逻辑(例如日志记录)。

分解它

  1. 代理对象:这些是动态创建的对象,代表您的实际业务对象,通过方法处理程序路由方法调用。
  2. 调用处理程序:这就是拦截的神奇之处。使用反射,处理程序可以检查目标方法上存在的注释并相应地改变行为。
  3. 自定义注释:您可以定义自定义注释,它们用作触发日志记录、安全检查或事务管理等附加功能的标记。

示例: 假设我们想在某些方法执行之前和之后添加日志记录。我们可以使用 @beforemethod 和 @aftermethod 注释方法,而不是到处硬编码日志记录。我们的处理程序检查此注释的方法并动态添加适当的日志记录逻辑。

下面是我们示例中控制器和服务的类。

workercontroller.java

package edu.pk.poc.aop.controller;

import edu.pk.poc.aop.annotation.aftermethod;
import edu.pk.poc.aop.annotation.all;
import edu.pk.poc.aop.annotation.beforemethod;
import edu.pk.poc.aop.helper.proxyfactory;
import edu.pk.poc.aop.service.worker;
import edu.pk.poc.aop.service.workerservice;
import edu.pk.poc.aop.service.workerserviceimpl;

public class workercontroller {
    workerservice workerservice = proxyfactory.createproxy(workerserviceimpl.class);
    /**
     * this method 1s annotated with @beforemethod and @aftermethod, so the log statements
     * will be generated before and after method call.
     */
    @beforemethod
    @aftermethod
    public void engagefulltimeworker() throws exception {
        worker fulltimeworker = new worker();
        fulltimeworker.setname("fulltime-worker");
        fulltimeworker.setparttime(false);
        fulltimeworker.setduration(9);
        workerservice.dowork(fulltimeworker);
    }
    /**
     * this method is annotated with @all, so the log statements will be generated before and after method call
     * along with exception if raised.
     */
    @all
    public void engageparttimeworker() throws exception {
        worker parttimeworker = new worker();
        parttimeworker.setname("parttime-worker");
        parttimeworker.setparttime(true);
        parttimeworker.setduration(4);
        workerservice.dowork(parttimeworker);
    }
}

workerserviceimpl.java

package edu.pk.poc.aop.service;

import edu.pk.poc.aop.annotation.aftermethod;

public class workerserviceimpl implements workerservice {
    /**
     * here this method is annotated with only @aftermethod, so only log statement
     * will be generated after method call
     */
    @aftermethod
    @override
    public void dowork(worker worker) throws exception {
        if (worker.isparttime()) {
            throw new exception("part time workers are not permitted to work.");
        }
        system.out.print("a full time worker is working for " + worker.getduration() + " hours :: ");
        for (int i = 1; i < worker.getduration(); i++) {
            system.out.print("* ");
        }
        system.out.println();
    }
}

main.java 测试类

AIBox 一站式AI创作平台
AIBox 一站式AI创作平台

AIBox365一站式AI创作平台,支持ChatGPT、GPT4、Claue3、Gemini、Midjourney等国内外大模型

下载
package edu.pk.poc.aop.test;

import edu.pk.poc.aop.controller.workercontroller;
import edu.pk.poc.aop.helper.proxyfactory;
import edu.pk.util.logger;

public class main {
    public static void main(string[] args) {
        workercontroller controller = proxyfactory.createproxy(workercontroller.class);
        logger logger = new logger();
        try {
            system.out.println("testing @beforemethod and @aftermethod");
            system.out.println("-----------------------------------------");
            controller.engagefulltimeworker();
            system.out.println("testing @all");
            system.out.println("-----------------------------------------");
            controller.engageparttimeworker();
        } catch (exception e) {
            logger.error("exception caught in main class");
        }
    }
}

输出

testing @beforemethod and @aftermethod
-----------------------------------------
>>> entering into edu.pk.poc.aop.controller.workercontroller.engagefulltimeworker()
a full time worker is working for 9 hours :: * * * * * * * * 
>>> exiting from edu.pk.poc.aop.service.workerserviceimpl.dowork()
>>> exiting from edu.pk.poc.aop.controller.workercontroller.engagefulltimeworker()
testing @all
-----------------------------------------
>>> entering into edu.pk.poc.aop.controller.workercontroller.engageparttimeworker()
>>> exception in edu.pk.poc.aop.controller.workercontroller.engageparttimeworker()
exception caught in main class

它是如何运作的

当在代理对象上调用方法时,该调用会被处理程序拦截,处理程序使用反射来检查目标方法上的所有注释。根据这些注释,处理程序决定是否记录方法进入/退出、记录异常或完全跳过记录。

以下是可视化它的方法:

  • 执行前:记录方法条目。
  • 执行后:记录方法退出或成功。
  • 全部:记录方法条目、方法条目以及引发的异常。 这种动态行为表明 spring aop 利用了核心 java api,而不是使用一些神奇的技巧。

定义注释

package edu.pk.poc.aop.annotation;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

@retention(retentionpolicy.runtime)
@target(elementtype.method)
public @interface aftermethod {

}
package edu.pk.poc.aop.annotation;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

@retention(retentionpolicy.runtime)
@target(elementtype.method)
public @interface beforemethod {

}
package edu.pk.poc.aop.annotation;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

@retention(retentionpolicy.runtime)
@target(elementtype.method)
public @interface all {

}

定义代理工厂

package edu.pk.poc.aop.helper;

/**
 * the {@code proxyfactory} class is responsible for creating proxy objects using the javassist library.
 * it allows for dynamic generation of proxies for classes or interfaces, with support for method interception.
 */
public class proxyfactory {

    /**
     * a javassist proxyfactory instance used to generate proxy classes.
     */
    private static final javassist.util.proxy.proxyfactory factory = new javassist.util.proxy.proxyfactory();

    /**
     * creates a proxy object for the given class or interface.
     * if the class is an interface, the proxy implements the interface.
     * if it's a concrete class, the proxy extends the class.
     *
     * @param <t>   the type of the class or interface for which the proxy is to be created
     * @param klass the {@code class} object representing the class or interface to proxy
     * @return a proxy instance of the specified class or interface, or {@code null} if proxy creation fails
     */
    public static <t> t createproxy(class<t> klass) {
        if (klass.isinterface())
            factory.setinterfaces(new class[]{klass});
        else
            factory.setsuperclass(klass);
        try {
            return (t) factory.create(new class<?>[0], new object[0], new aoploggingmethodhandler());
        } catch (exception e) {
            system.err.println(e.getmessage());
        }
        return null;
    }
}

定义 methodhandler

package edu.pk.poc.aop.helper;

import edu.pk.poc.aop.annotation.AfterMethod;
import edu.pk.poc.aop.annotation.All;
import edu.pk.poc.aop.annotation.BeforeMethod;
import edu.pk.poc.aop.annotation.OnException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import edu.pk.util.Logger;
import javassist.util.proxy.MethodHandler;

public class AOPLoggingMethodHandler implements MethodHandler {

    private static final Logger logger = new Logger();

    public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
        if (proceed != null) { // Concrete Method
            Object result = null;
            String className = resolveClassName(self);
            try {
                if (isAnnotationPresent(thisMethod, BeforeMethod.class) || isAnnotationPresent(thisMethod, All.class)) {
                    logger.info(">>> Entering into " + className + "." + thisMethod.getName() + "()");
                }
                result = proceed.invoke(self, args);
                if (isAnnotationPresent(thisMethod, AfterMethod.class) || isAnnotationPresent(thisMethod, All.class)) {
                    logger.info(">>> Exiting from " + className + "." + thisMethod.getName() + "()");
                }
            } catch (Throwable t) {
                if (isAnnotationPresent(thisMethod, OnException.class) || isAnnotationPresent(thisMethod, All.class)) {
                    logger.error(">>> Exception in " + className + "." + thisMethod.getName() + "()");
                }
                throw t;
            }
            return result;
        }
        throw new RuntimeException("Method is Abstract");
    }

    private boolean isAnnotationPresent(Method method, Class klass) {
        Annotation[] declaredAnnotationsByType = method.getAnnotationsByType(klass);
        return declaredAnnotationsByType != null && declaredAnnotationsByType.length > 0;
    }

    private String resolveClassName(Object self) {
        String className = self.getClass().getName();
        if (className.contains("_$$")) {
            className = className.substring(0, className.indexOf("_$$"));
        }
        return className;
    }
}

结论

spring aop 是一个用于横切关注点的强大工具,但它并没有做任何革命性的事情。它建立在反射和代理等核心 java 概念之上,这些概念在语言本身中可用。通过理解这一点,您可以更好地理解 spring 如何简化这些底层机制以方便开发人员。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

161

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

89

2026.01.26

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

25

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

44

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

177

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

50

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

92

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

102

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

227

2026.03.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Servlet基础教程
Servlet基础教程

共24课时 | 19.5万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号