aop

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 16 Imported by: 0

README

aop 包 — 面向切面编程

所属层级: Core Layer
设计理念: 横切关注点分离,动态代理
设计灵感: Spring AOP

概述

aop 包提供一个轻量级的面向切面编程(AOP)框架,允许开发者通过切面(Aspect)将横切关注点(如日志、事务、权限检查)与业务逻辑分离。

核心概念
概念 说明
Advice(通知) 在特定连接点执行的增强逻辑
PointCut(切点) 定义哪些方法需要被拦截的匹配规则
Advisor(顾问) 切点 + 通知的组合单元
AspectMeta(切面元数据) 切面的完整描述,包含切点、通知和执行顺序
Weaver(织入器) 将切面织入目标对象,生成代理对象
JoinPoint(连接点) 程序执行的某个位置(如方法调用)
通知类型
类型 常量 执行时机 用途
前置通知 AdviceBefore 目标方法执行之前 日志、权限检查
后置通知 AdviceAfter 目标方法执行之后(无论是否异常) 资源清理
返回通知 AdviceAfterReturning 目标方法正常返回之后 结果处理
异常通知 AdviceAfterThrowing 目标方法抛出异常之后 异常处理
环绕通知 AdviceAround 包裹整个目标方法,可控制方法执行 事务、性能监控

核心接口

Advice 接口
type Advice interface {
    Type() AdviceType                              // 返回通知类型
    Apply(jp JoinPoint, proceed ProceedFunc) any   // 应用通知逻辑
}
PointCut 接口
type PointCut interface {
    MatchClass(c reflect.Type) bool     // 匹配类
    MatchMethod(m reflect.Method) bool  // 匹配方法
}
Advisor 接口
type Advisor interface {
    GetPointCut() PointCut
    GetAdvice() Advice
    Order() int
}
AspectMeta 结构体
type AspectMeta struct {
    Instance any        // 切面实例
    PointCut PointCut  // 切点
    Advice   Advice    // 通知
    Order    int       // 执行顺序,值越小优先级越高
}
JoinPoint 接口
type JoinPoint interface {
    Method() any                // 获取被拦截的方法
    Args() []any                // 获取方法调用参数
    Signature() MethodSignature // 获取方法签名
    This() any                  // 获取代理对象
    Target() any                // 获取目标对象
}

type MethodSignature interface {
    Name() string               // 方法名
    DeclaringType() reflect.Type // 声明方法的类型
}
Weaver 接口
type Weaver interface {
    Weave(target any) any                        // 织入目标,返回代理
    AddAspects(aspects ...*AspectMeta)           // 添加切面
}

快速开始

创建通知
// 前置通知
beforeAdvice := aop.Before(func(jp aop.JoinPoint) {
    fmt.Println("方法执行前:", jp.Signature().Name())
})

// 后置通知
afterAdvice := aop.After(func(jp aop.JoinPoint) {
    fmt.Println("方法执行后:", jp.Signature().Name())
})

// 返回通知
returningAdvice := aop.AfterReturning(func(jp aop.JoinPoint, result any) {
    fmt.Println("方法返回:", result)
})

// 异常通知
throwingAdvice := aop.AfterThrowing(func(jp aop.JoinPoint, err error) {
    fmt.Println("方法异常:", err)
})

// 环绕通知
aroundAdvice := aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
    fmt.Println("方法执行前")
    result := proceed()
    fmt.Println("方法执行后")
    return result
})
创建切点
// 匹配所有方法
aop.MatchAll()

// 按方法名精确匹配
aop.MatchByName("DoSomething")

// 按方法名前缀匹配
aop.MatchByNamePrefix("Get")

// 按正则表达式匹配
aop.MatchByRegex("(?i)^do.*")

// 自定义匹配器组合
aop.MatchClassMethod(
    func(t reflect.Type) bool {
        return t.Name() == "UserService"
    },
    func(m reflect.Method) bool {
        return m.Name == "DoSomething"
    },
)
创建 Advisor
advisor := aop.NewAdvisor(
    aop.MatchByName("DoSomething"),
    aop.Before(func(jp aop.JoinPoint) {
        fmt.Println("执行前:", jp.Signature().Name())
    }),
    1, // 可选顺序参数,值越小优先级越高
)
织入目标对象
// 创建织入器
weaver := aop.NewWeaver()

// 添加切面
weaver.AddAspects(
    &aop.AspectMeta{
        PointCut: aop.MatchByName("DoSomething"),
        Advice:   aop.Before(func(jp aop.JoinPoint) { fmt.Println("before") }),
        Order:    1,
    },
)

// 织入目标对象,返回代理
target := &UserService{}
proxy := weaver.Weave(target)

// 使用代理对象,通知会自动执行
proxy.(*UserService).DoSomething()
// 输出: before
// 输出: DoSomething did it

API 参考

通知创建函数
函数 说明 示例
Before(fn) 创建前置通知 aop.Before(func(jp JoinPoint) { ... })
After(fn) 创建后置通知 aop.After(func(jp JoinPoint) { ... })
AfterReturning(fn) 创建返回通知 aop.AfterReturning(func(jp JoinPoint, result any) { ... })
AfterThrowing(fn) 创建异常通知 aop.AfterThrowing(func(jp JoinPoint, err error) { ... })
Around(fn) 创建环绕通知 aop.Around(func(jp JoinPoint, proceed ProceedFunc) any { ... })
切点匹配器函数
函数 说明 示例
MatchAll() 匹配所有类和方法 aop.MatchAll()
MatchByName(name) 按方法名精确匹配 aop.MatchByName("GetUser")
MatchByNamePrefix(prefix) 按方法名前缀匹配 aop.MatchByNamePrefix("Get")
MatchByRegex(pattern) 按正则表达式匹配方法名 aop.MatchByRegex("^Get.*$")
MatchClass(matcher) 自定义类匹配器 aop.MatchClass(func(t reflect.Type) bool { ... })
MatchMethod(matcher) 自定义方法匹配器 aop.MatchMethod(func(m reflect.Method) bool { ... })
MatchClassMethod(class, method) 同时匹配类和方法 aop.MatchClassMethod(classMatcher, methodMatcher)
MatchByAnnotation(annotationType) 按注解类型匹配 aop.MatchByAnnotation(reflect.TypeOf((*Transactional)(nil)).Elem())
MatchInterface(iface) 匹配实现指定接口的类 aop.MatchInterface((*ServiceInterface)(nil))
排序函数
// 按 Order 值升序排列切面列表
aop.SortAspectsByOrder(aspects)
InterfaceProxyWrapper

接口代理包装器,通过反射转发接口方法调用,支持 AOP 切面织入:

type InterfaceProxyWrapper struct {
    target      any
    advisors    []*AspectMeta
    iface       reflect.Type
    methodCache map[string]reflect.Method
    cacheMu     sync.RWMutex
    executor    ChainExecutor
}

主要方法:

// 调用指定方法(不带上下文)
func (w *InterfaceProxyWrapper) Invoke(methodName string, args ...any) (any, error)

// 带上下文的方法调用
func (w *InterfaceProxyWrapper) InvokeContext(ctx context.Context, methodName string, args ...any) (any, error)

// 返回原始目标对象
func (w *InterfaceProxyWrapper) Unwrap() any

使用示例

日志切面
// 创建日志切面
logAspect := &aop.AspectMeta{
    PointCut: aop.MatchByNamePrefix("Get"),
    Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
        start := time.Now()
        fmt.Printf("调用方法: %s\n", jp.Signature().Name())
        result := proceed()
        fmt.Printf("方法执行耗时: %v\n", time.Since(start))
        return result
    }),
    Order: 1,
}

// 织入目标
weaver := aop.NewWeaver()
weaver.AddAspects(logAspect)
proxy := weaver.Weave(&UserService{})
事务切面
// 创建事务切面
txAspect := &aop.AspectMeta{
    PointCut: aop.MatchByAnnotation(reflect.TypeOf((*Transactional)(nil)).Elem()),
    Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
        tx := db.Begin()
        defer func() {
            if r := recover(); r != nil {
                tx.Rollback()
                panic(r)
            }
        }()
        result := proceed()
        tx.Commit()
        return result
    }),
    Order: 1,
}
权限检查切面
// 创建权限检查切面
authAspect := &aop.AspectMeta{
    PointCut: aop.MatchByNamePrefix("Admin"),
    Advice: aop.Before(func(jp aop.JoinPoint) {
        // 检查用户是否有管理员权限
        if !hasAdminPermission() {
            panic("access denied")
        }
    }),
    Order: 1,
}
性能监控切面
// 创建性能监控切面
perfAspect := &aop.AspectMeta{
    PointCut: aop.MatchAll(),
    Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
        start := time.Now()
        result := proceed()
        duration := time.Since(start)
        
        // 记录性能指标
        metrics.RecordMethodDuration(jp.Signature().Name(), duration)
        
        return result
    }),
    Order: 1,
}

最佳实践

1. 合理使用通知类型
  • Before:用于方法执行前的准备工作(参数验证、权限检查)
  • After:用于资源清理(无论是否异常都会执行)
  • AfterReturning:用于处理正常返回值(结果转换、缓存)
  • AfterThrowing:用于异常处理(日志记录、告警)
  • Around:用于完全控制方法执行(事务、性能监控)
2. 注意切面执行顺序

Order 值越小,优先级越高。合理设置 Order 确保切面按预期顺序执行:

// 权限检查应该最先执行
authAspect := &aop.AspectMeta{Order: 1, ...}

// 日志记录其次
logAspect := &aop.AspectMeta{Order: 2, ...}

// 性能监控最后执行
perfAspect := &aop.AspectMeta{Order: 3, ...}
3. 避免在通知中抛出异常

在 Before/After/AfterReturning 通知中抛出异常会中断后续通知和目标方法的执行。建议在通知中捕获并处理异常:

aop.Before(func(jp aop.JoinPoint) {
    defer func() {
        if r := recover(); r != nil {
            log.Printf("通知执行异常: %v", r)
        }
    }()
    // 通知逻辑
})
4. 使用 Around 通知时务必调用 proceed

环绕通知必须调用 proceed() 继续执行目标方法或下一个通知,否则目标方法不会被执行:

aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
    // 前置逻辑
    result := proceed() // ⚠️ 必须调用
    // 后置逻辑
    return result
})
5. 切点匹配规则建议
  • 使用 MatchByNamePrefix 匹配一组相关方法
  • 使用 MatchByRegex 进行复杂模式匹配
  • 使用 MatchClassMethod 精确控制匹配的类和方法
  • 避免使用 MatchAll() 除非确实需要拦截所有方法

ChainExecutor(链执行器)

ChainExecutor 负责执行 AOP 通知链,按照正确的顺序执行各种类型的通知:

type ChainExecutor struct{}

// Execute 执行通知链
func (e *ChainExecutor) Execute(inv Invocation, advisors []*AspectMeta, targetFunc func(...any) any) any
通知执行顺序
Before 通知(按 Order 升序)
    ↓
Around 通知链(最外层到最内层)
    ↓
目标方法执行
    ↓
AfterReturning 通知(正常返回)或 AfterThrowing 通知(异常返回)
    ↓
After 通知(无论是否异常都执行)
设计优化
  • 指针版本:统一使用 []*AspectMeta 指针版本,避免值类型到指针的转换开销
  • 错误查找:AfterThrowing 通知从后往前检查多返回值中的 error,符合 Go 错误返回惯例

ProxyFactory(代理工厂)

ProxyFactory 负责创建 AOP 代理对象,支持缓存和通知链:

// 创建代理工厂
factory := aop.NewProxyFactory(target)

// 设置切面
factory.SetAspects(aspects)

// 获取代理对象
proxy := factory.GetProxy()
缓存机制

ProxyFactory 会缓存方法匹配的切面列表,避免每次调用都重新匹配和排序。使用 sync.RWMutex 保证并发安全。


AopRegistry(AOP 注册表)

AopRegistry 是一个全局 AOP 配置中心,用于在 IoC 容器中集成 AOP:

registry := aop.NewAopRegistry()

// 注册切面
registry.RegisterAspect(aspectMeta)

// 注册织入器
registry.RegisterWeaver("userService", weaver)

// 按需织入
proxy := registry.WeaveIfNeeded("userService", &UserService{})

// 为类型匹配切面
matched := registry.MatchAspectsForType(reflect.TypeOf(&UserService{}))

装饰器(Decorator)

框架还提供函数级别的装饰器,用于简单的 AOP 场景:

// 前置装饰器
decorated := aop.BeforeDecorator(
    func(args ...any) []any {
        // 原始函数逻辑
        return []any{"result"}
    },
    func(args ...any) {
        fmt.Println("before")
    },
)

// 后置装饰器
decorated := aop.AfterDecorator(
    originalFunc,
    func(results []any, args ...any) {
        fmt.Println("after, result:", results)
    },
)

// 环绕装饰器
decorated := aop.AroundDecorator(
    originalFunc,
    func(originalFunc func(args ...any) []any, args ...any) []any {
        fmt.Println("around before")
        results := originalFunc(args...)
        fmt.Println("around after")
        return results
    },
)

通知执行顺序

当目标方法被调用时,通知按以下顺序执行:

Before 通知(按 Order 升序)
    ↓
Around 通知链(最外层到最内层)
    ↓
目标方法本身
    ↓
After / AfterReturning / AfterThrowing 通知(按 Order 升序)

多个切面之间按 Order 值升序排列。Order 值相同的切面按照添加顺序执行。


完整示例

package main

import (
    "fmt"
    "github.com/xudefa/enhance/aop"
)

// LogAspect 日志切面
type LogAspect struct{}

func (l *LogAspect) BeforeLog(jp aop.JoinPoint) {
    fmt.Printf("[日志] 方法 %s 被调用,参数: %v\n",
        jp.Signature().Name(), jp.Args())
}

func (l *LogAspect) AfterLog(jp aop.JoinPoint) {
    fmt.Printf("[日志] 方法 %s 执行完毕\n",
        jp.Signature().Name())
}

// UserService 业务服务
type UserService struct {
    Name string
}

func (u *UserService) CreateUser(name string) string {
    fmt.Println("创建用户:", name)
    return "user_" + name
}

func (u *UserService) DeleteUser(id string) {
    fmt.Println("删除用户:", id)
}

func main() {
    aspect := &LogAspect{}

    // 创建切点 — 匹配所有以 User 结尾的方法
    pointCut := aop.MatchByRegex(".*User$")

    // 创建前置通知
    beforeAdvice := aop.Before(aspect.BeforeLog)

    // 创建后置通知
    afterAdvice := aop.After(aspect.AfterLog)

    // 创建切面元数据
    beforeAspect := &aop.AspectMeta{
        PointCut: pointCut,
        Advice:   beforeAdvice,
        Order:    1,
    }
    afterAspect := &aop.AspectMeta{
        PointCut: pointCut,
        Advice:   afterAdvice,
        Order:    2,
    }

    // 创建织入器
    weaver := aop.NewWeaver()
    weaver.AddAspects(beforeAspect, afterAspect)

    // 织入目标
    proxy := weaver.Weave(&UserService{Name: "test"})

    // 使用代理
    userSvc := proxy.(*UserService)
    result := userSvc.CreateUser("Alice") // 触发 before → 原方法 → after
    fmt.Println("结果:", result)

    userSvc.DeleteUser("123") // 同样触发 before → 原方法 → after
}

预计输出:

[日志] 方法 CreateUser 被调用,参数: [Alice]
创建用户: Alice
[日志] 方法 CreateUser 执行完毕
结果: user_Alice
[日志] 方法 DeleteUser 被调用,参数: [123]
删除用户: 123
[日志] 方法 DeleteUser 执行完毕

与 IoC 容器集成

AopRegistry 可以轻松与 core.Container 集成,实现 Bean 自动代理:

registry := aop.NewAopRegistry()

// 注册日志切面
registry.RegisterAspect(&aop.AspectMeta{
    PointCut: aop.MatchByRegex(".*Service\\..*"),
    Advice:   aop.Before(func(jp aop.JoinPoint) { fmt.Println("before") }),
    Order:    0,
})

// 注册 Bean 时织入
container.Register(
    reflect.TypeOf(&UserService{}),
    core.Factory(func(c core.Container) (any, error) {
        svc := &UserService{}
        // 通过 AopRegistry 按需织入
        return registry.WeaveIfNeeded("userService", svc), nil
    }, reflect.TypeOf(&UserService{})),
)

通知链执行机制

当多个 Around 通知作用于同一方法时,它们会组成一个嵌套的调用链。每个 Around 通知可以通过 proceed 控制是否以及如何调用下一个通知:

// 最外层 Around(Order=1)
chain1 := aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
    fmt.Println("chain1 before")
    result := proceed()           // 调用 chain2
    fmt.Println("chain1 after")
    return result
})

// 内层 Around(Order=2)
chain2 := aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
    fmt.Println("chain2 before")
    result := proceed()           // 调用目标方法
    fmt.Println("chain2 after")
    return result
})

执行顺序:

chain1 before → chain2 before → 目标方法 → chain2 after → chain1 after

使用场景

场景 1:日志记录

描述:记录方法调用日志,包括方法名、参数、返回值等。

factory := aop.NewProxyFactory(service)
factory.SetAspects([]*aop.AspectMeta{
	{
		PointCut: aop.MatchAll(),
		Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
			start := time.Now()
			result := proceed()
			duration := time.Since(start)
			log.Printf("Method %s called, args: %v, result: %v, duration: %v",
				jp.Signature().Name(), jp.Args(), result, duration)
			return result
		}),
		Order: 1,
	},
})

最佳实践

  • 使用环绕通知记录完整调用信息
  • 记录方法执行时间用于性能分析
  • 避免记录敏感信息
场景 2:事务管理

描述:声明式事务管理,自动提交或回滚事务。

factory := aop.NewProxyFactory(service)
factory.SetAspects([]*aop.AspectMeta{
	{
		PointCut: aop.MatchByNamePrefix("Update"),
		Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
			tx := db.Begin()
			defer func() {
				if r := recover(); r != nil {
					tx.Rollback()
					panic(r)
				}
			}()

			result := proceed()

			if err := getError(result); err != nil {
				tx.Rollback()
				return result
			}

			tx.Commit()
			return result
		}),
		Order: 1,
	},
})

最佳实践

  • 使用环绕通知控制事务边界
  • 确保异常时回滚事务
  • 避免在事务中执行耗时操作
场景 3:安全控制

描述:检查用户权限,拦截未授权访问。

factory := aop.NewProxyFactory(service)
factory.SetAspects([]*aop.AspectMeta{
	{
		PointCut: aop.MatchByNamePrefix("Delete"),
		Advice: aop.Before(func(jp aop.JoinPoint) {
			if !hasPermission(jp.Args()[0].(string), "delete") {
				panic("permission denied")
			}
		}),
		Order: 1,
	},
})

最佳实践

  • 使用前置通知进行权限检查
  • 权限检查逻辑应高效
  • 记录权限拒绝日志
场景 4:缓存管理

描述:缓存方法结果,减少重复计算。

cache := make(map[string]any)

factory := aop.NewProxyFactory(service)
factory.SetAspects([]*aop.AspectMeta{
	{
		PointCut: aop.MatchByNamePrefix("Get"),
		Advice: aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
			key := fmt.Sprintf("%s:%v", jp.Signature().Name(), jp.Args())
			if cached, ok := cache[key]; ok {
				return cached
			}

			result := proceed()
			cache[key] = result
			return result
		}),
		Order: 1,
	},
})

最佳实践

  • 使用环绕通知实现缓存逻辑
  • 缓存键应包含方法名和参数
  • 考虑缓存失效策略

Documentation

Overview

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持,用于 enhance 框架。

该模块提供完整的 AOP 实现,包括通知、切点、顾问器、动态代理等功能。 支持静态代理代码生成,提升运行时性能。

架构设计

  • Advice: 通知接口(Before/After/AfterReturning/AfterThrowing/Around)
  • PointCut: 切点定义,支持方法名、包名、注解匹配
  • Advisor: 顾问器,组合切点和通知
  • Proxy: 动态代理生成
  • Aspect: 切面定义和管理
  • 代码生成: 支持静态代理代码生成

使用方式

直接使用:

// 创建切面
aspect := aop.NewAspect("loggingAspect").
    AddAdvice(aop.BeforeAdvice(func(ctx aop.JoinPoint) {
        fmt.Println("Before:", ctx.MethodName())
    }))

// 创建代理
proxy := aop.NewProxy(target, aspect)

代码生成

使用 go generate 生成静态代理代码:

//go:generate go run github.com/xudefa/enhance/cmd/goaop

支持的匹配模式

  • 方法名匹配:支持通配符(*)
  • 包名匹配:支持包路径前缀匹配
  • 注解匹配:基于方法注解进行匹配

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。

Package aop 提供面向切面编程(AOP)支持。 ProxyFactory 结构体定义在 doc.go 中,此处为实现。

Package aop 提供面向切面编程(AOP)支持。 InterfaceProxyWrapper 结构体定义在 doc.go 中,此处为实现。

Package aop 提供面向切面编程(AOP)支持。

Index

Constants

This section is empty.

Variables

View Source
var GlobalAopBeanFactory = NewAopBeanFactory(nil)

GlobalAopBeanFactory 全局AOP Bean工厂

View Source
var GlobalAopBeanPostProcessor = NewAopBeanPostProcessor(nil)

GlobalAopBeanPostProcessor 全局AOP Bean后置处理器

View Source
var GlobalAopBeanScanner = NewAopBeanScanner(nil)

GlobalAopBeanScanner 全局AOP Bean扫描器

View Source
var GlobalAopIntegration = NewAopIntegration(nil)

GlobalAopIntegration 全局AOP集成器

View Source
var GlobalAopManager = &AopManager{
	config:  DefaultAopConfig(),
	aspects: make([]*AspectMeta, 0),
}

GlobalAopManager 全局AOP管理器。

View Source
var GlobalAopMetrics = NewAopMetrics()

GlobalAopMetrics 全局AOP指标

View Source
var GlobalBuildTagChecker = NewBuildTagChecker()

GlobalBuildTagChecker 全局构建标签检查器

View Source
var GlobalGeneratedProxyRegistry = NewGeneratedProxyRegistry()

GlobalGeneratedProxyRegistry 全局代码生成代理注册表

Functions

func AfterDecorator

func AfterDecorator(f func(args ...any) []any, after func(results []any, args ...any)) func(args ...any) []any

AfterDecorator 创建后置装饰器,在调用原函数后执行 after 钩子。

参数:

  • f: 被装饰的函数
  • after: 后置钩子函数,接收 f 的所有参数和所有返回值

返回值:

  • func(args ...any) []any: 装饰后的函数

func AroundDecorator

func AroundDecorator(f func(args ...any) []any, around AroundFunc) func(args ...any) []any

AroundDecorator 创建环绕装饰器,由 around 函数完全控制原函数的执行流程。

参数:

  • f: 被装饰的函数
  • around: 环绕函数,接收原始函数 f 和原始参数,决定是否调用 f 以及在调用前后插入逻辑

返回值:

  • func(args ...any) []any: 装饰后的函数

func AutoRegister

func AutoRegister(beanID string) error

AutoRegister 自动注册切面

从代码生成的代理中自动提取并注册切面

func AutoRegisterAll

func AutoRegisterAll() error

AutoRegisterAll 自动注册所有切面

从所有代码生成的代理中自动提取并注册切面

func AutoScan

func AutoScan() error

AutoScan 自动扫描

func BeforeDecorator

func BeforeDecorator(f func(args ...any) []any, before func(args ...any)) func(args ...any) []any

BeforeDecorator 创建前置装饰器,在调用原函数前执行 before 钩子。

参数:

  • f: 被装饰的函数,签名为 func(args ...any) []any
  • before: 前置钩子函数,接收 f 的所有参数

返回值:

  • func(args ...any) []any: 装饰后的函数

func CreateProxy

func CreateProxy(beanID string, target any) any

CreateProxy 创建代理对象(使用全局集成器)

func ExecuteChain

func ExecuteChain(jp *MethodInvocation, aspects []*AspectMeta) any

ExecuteChain 执行通知链

为代码生成的代理类提供通知链执行功能。 按照切面的 Order 排序,通过默认 ChainExecutor 执行通知链。

参数:

  • jp: 方法调用信息
  • aspects: 切面元数据列表(指针类型)

返回值:

  • any: 方法执行结果

func GetGeneratedProxy

func GetGeneratedProxy(beanID string) (reflect.Type, bool)

GetGeneratedProxy 获取代码生成的代理类型

func GetGlobalAopMetrics

func GetGlobalAopMetrics() map[string]any

GetGlobalAopMetrics 获取全局AOP指标

func GetProxyWithAutoMode

func GetProxyWithAutoMode(beanID string, target any) any

GetProxyWithAutoMode 使用自动模式获取代理

func HasGeneratedProxy

func HasGeneratedProxy(beanID string) bool

HasGeneratedProxy 检查是否存在代码生成的代理

func InitializeAop

func InitializeAop()

InitializeAop 初始化AOP

自动配置并初始化AOP系统

func IsReflectiveProxy

func IsReflectiveProxy(obj any) bool

IsReflectiveProxy 检查对象是否为 ReflectiveAopProxy

func ParseAspectTarget

func ParseAspectTarget(target string) (structName, methodName string, err error)

ParseAspectTarget 解析切面目标

解析类似 "UserService.GetUser" 的目标字符串

func RegisterAopBeanToGlobal

func RegisterAopBeanToGlobal(beanID string, beanType reflect.Type, target any) error

RegisterAopBeanToGlobal 注册AOP Bean到全局容器

func RegisterAspectToGlobal

func RegisterAspectToGlobal(aspect *AspectMeta)

RegisterAspectToGlobal 注册切面到全局集成器

func RegisterAspectToGlobalContainer

func RegisterAspectToGlobalContainer(aspect *AspectMeta)

RegisterAspectToGlobalContainer 注册切面到全局容器

func RegisterGeneratedProxy

func RegisterGeneratedProxy(beanID string, proxyType reflect.Type)

RegisterGeneratedProxy 注册代码生成的代理

func ResetGlobalAopMetrics

func ResetGlobalAopMetrics()

ResetGlobalAopMetrics 重置全局AOP指标

func ScanAopBeans

func ScanAopBeans(basePath string) error

ScanAopBeans 扫描AOP Bean

func SetDefaultChainExecutor

func SetDefaultChainExecutor(executor ChainExecutor)

SetDefaultChainExecutor 设置默认通知链执行器

传入 nil 会被忽略。设置后,所有使用默认执行器的代码(包括 ExecuteChain 和 ReflectiveAopProxy) 都会使用新的执行器。并发安全。

func SortAspectsByOrder

func SortAspectsByOrder(aspects []*AspectMeta)

SortAspectsByOrder 按 Order 升序排序切面列表。

使用标准库 slices.SortFunc 按 Order 升序排列切面,Order 小的在前。 当多个切点匹配同一方法时,通过 Order 控制通知的执行顺序。

Types

type Advice

type Advice interface {
	// Type 返回通知类型。
	Type() AdviceType

	// Apply 应用通知。
	//
	// 执行通知的增强逻辑。对于 Around 通知,需要通过 proceed 参数
	// 调用目标方法或下一个通知。
	//
	// 参数:
	//   - jp: 连接点,包含方法调用的上下文信息(方法名、参数、目标对象等)
	//   - proceed: 继续执行函数,调用它会执行目标方法或下一个通知
	//
	// 返回值:
	//   - any: 通知的返回值。对于 Around 通知,通常返回目标方法的执行结果;
	//     对于其他通知类型,返回值通常被忽略。
	Apply(jp JoinPoint, proceed ProceedFunc) any
}

Advice 通知接口。

定义 AOP 通知的核心行为。通知是对目标方法的增强逻辑, 在方法执行的生命周期中的特定时机介入。

推荐使用 Before/After/Around 等函数式 API 替代直接实现此接口, 以获得更简洁的 Go 惯用法体验。此接口主要用于框架内部实现。

func After

func After(fn func(JoinPoint)) Advice

After 创建后置通知

在目标方法执行之后执行增强逻辑,无论方法是否抛出异常。 后置通知在异常通知之前执行。

参数:

  • fn: 后置通知函数,接收 JoinPoint 参数

返回值:

  • Advice: 后置通知实例

示例:

aop.After(func(jp aop.JoinPoint) {
    fmt.Println("方法执行后:", jp.Method().Name)
})

func AfterReturning

func AfterReturning(fn func(JoinPoint, any)) Advice

AfterReturning 创建返回通知

在目标方法正常返回后执行增强逻辑。 可以访问方法的返回值,适用于结果缓存、响应增强等场景。 如果方法抛出异常,此通知不会执行。

参数:

  • fn: 返回通知函数,接收 JoinPoint 和方法返回值

返回值:

  • Advice: 返回通知实例

示例:

aop.AfterReturning(func(jp aop.JoinPoint, result any) {
    fmt.Println("方法返回:", result)
})

func AfterThrowing

func AfterThrowing(fn func(JoinPoint, error)) Advice

AfterThrowing 创建异常通知

在目标方法抛出异常后执行增强逻辑。 可以访问错误对象,适用于错误日志、异常转换、告警通知等场景。 如果方法正常返回,此通知不会执行。

参数:

  • fn: 异常通知函数,接收 JoinPoint 和错误对象

返回值:

  • Advice: 异常通知实例

示例:

aop.AfterThrowing(func(jp aop.JoinPoint, err error) {
    fmt.Println("方法异常:", err)
})

func Around

func Around(fn func(JoinPoint, ProceedFunc) any) Advice

Around 创建环绕通知

最强大的通知类型,完全控制目标方法的执行。 可以决定是否执行目标方法、何时执行、执行几次,甚至可以替换返回值。

重要:Around 通知必须调用 proceed 函数使调用链继续,否则目标方法不会执行。

参数:

  • fn: 环绕通知函数,接收 JoinPoint 和 ProceedFunc

返回值:

  • Advice: 环绕通知实例

示例:

aop.Around(func(jp aop.JoinPoint, proceed aop.ProceedFunc) any {
    fmt.Println("方法执行前:", jp.Method().Name)
    result := proceed()
    fmt.Println("方法执行后:", result)
    return result
})

func Before

func Before(fn func(JoinPoint)) Advice

Before 创建前置通知

在目标方法执行之前执行增强逻辑。 前置通知无法修改方法参数或阻止方法执行。

参数:

  • fn: 前置通知函数,接收 JoinPoint 参数,可访问方法信息

返回值:

  • Advice: 前置通知实例

示例:

aop.Before(func(jp aop.JoinPoint) {
    fmt.Println("方法执行前:", jp.Method().Name)
})

type AdviceType

type AdviceType string

AdviceType 通知类型枚举。

定义 AOP 框架中的五种标准通知类型,对应 Spring AOP 的通知模型。 每种通知类型决定了增强逻辑在目标方法执行生命周期中的介入时机。

const (
	// AdviceBefore 前置通知。
	//
	// 在目标方法执行之前调用增强逻辑。
	// 适用于日志记录、参数校验、权限检查等场景。
	// 前置通知无法阻止目标方法的执行。
	AdviceBefore AdviceType = "before"

	// AdviceAfter 后置通知。
	//
	// 在目标方法执行之后调用,无论方法是否抛出异常。
	// 适用于资源清理、状态重置等场景。
	// 注意:后置通知在异常通知之前执行。
	AdviceAfter AdviceType = "after"

	// AdviceAfterReturning 返回通知。
	//
	// 在目标方法正常返回后调用(未抛出异常)。
	// 可以访问方法的返回值,适用于结果缓存、响应增强等场景。
	// 如果方法抛出异常,此通知不会执行。
	AdviceAfterReturning AdviceType = "after_returning"

	// AdviceAfterThrowing 异常通知。
	//
	// 在目标方法抛出异常后调用。
	// 可以访问错误对象,适用于错误日志、异常转换、告警通知等场景。
	// 如果方法正常返回,此通知不会执行。
	AdviceAfterThrowing AdviceType = "after_throwing"

	// AdviceAround 环绕通知。
	//
	// 最强大的通知类型,完全控制目标方法的执行。
	// 可以决定是否执行目标方法、何时执行、执行几次,甚至可以替换返回值。
	// 必须调用 proceed 函数使调用链继续,否则目标方法不会执行。
	// 适用于事务管理、性能监控、重试逻辑等场景。
	AdviceAround AdviceType = "around"
)

type Advisor

type Advisor interface {
	// GetPointCut 获取切点。
	GetPointCut() PointCut

	// GetAdvice 获取通知。
	GetAdvice() Advice

	// Order 获取执行顺序。
	Order() int
}

Advisor 顾问器接口。

顾问是 AOP 中的基本单元,包含一个切点和一个通知。 类似于 Spring 中的 Advisor 概念。

使用场景:

  • 细粒度的切面控制,为每个通知指定独立的切点和执行顺序
  • 精确控制通知执行顺序和匹配规则

func NewAdvisor

func NewAdvisor(pointCut PointCut, advice Advice, order ...int) Advisor

NewAdvisor 创建顾问

参数:

  • pointCut: 切点
  • advice: 通知
  • order: 可选的执行顺序,默认 0

返回值:

  • Advisor: 顾问实例

示例:

advisor := aop.NewAdvisor(
    aop.MatchByName("DoSomething"),
    aop.Before(func(jp aop.JoinPoint) { fmt.Println("before") }),
    1, // order
)

type AopBeanDefinition

type AopBeanDefinition struct {
	BeanID     string
	EnableAop  bool
	ProxyMode  AopMode
	TargetType reflect.Type
	ProxyType  reflect.Type
	Aspects    []*AspectMeta
}

AopBeanDefinition AOP Bean定义

扩展标准Bean定义,添加AOP相关配置

func NewAopBeanDefinition

func NewAopBeanDefinition(beanID string, beanType reflect.Type) *AopBeanDefinition

NewAopBeanDefinition 创建AOP Bean定义

func (*AopBeanDefinition) WithAopEnabled

func (d *AopBeanDefinition) WithAopEnabled(enabled bool) *AopBeanDefinition

WithAopEnabled 设置启用AOP

func (*AopBeanDefinition) WithAspects

func (d *AopBeanDefinition) WithAspects(aspects ...*AspectMeta) *AopBeanDefinition

WithAspects 设置切面

func (*AopBeanDefinition) WithProxyMode

func (d *AopBeanDefinition) WithProxyMode(mode AopMode) *AopBeanDefinition

WithProxyMode 设置代理模式

func (*AopBeanDefinition) WithProxyType

func (d *AopBeanDefinition) WithProxyType(proxyType reflect.Type) *AopBeanDefinition

WithProxyType 设置代理类型

type AopBeanFactory

type AopBeanFactory struct {
	// contains filtered or unexported fields
}

AopBeanFactory AOP Bean工厂

创建AOP代理Bean

func NewAopBeanFactory

func NewAopBeanFactory(integration *AopIntegration) *AopBeanFactory

NewAopBeanFactory 创建AOP Bean工厂

func (*AopBeanFactory) CreateBean

func (f *AopBeanFactory) CreateBean(beanID string, beanDef *AopBeanDefinition, target any) (any, error)

CreateBean 创建Bean

func (*AopBeanFactory) GetProcessor

func (f *AopBeanFactory) GetProcessor() *AopBeanPostProcessor

GetProcessor 获取后置处理器

func (*AopBeanFactory) RegisterBean

func (f *AopBeanFactory) RegisterBean(container core.Container, beanDef *AopBeanDefinition, target any) error

RegisterBean 注册Bean到容器

type AopBeanPostProcessor

type AopBeanPostProcessor struct {
	// contains filtered or unexported fields
}

AopBeanPostProcessor AOP Bean后置处理器

在Bean创建后自动应用AOP代理

func NewAopBeanPostProcessor

func NewAopBeanPostProcessor(integration *AopIntegration) *AopBeanPostProcessor

NewAopBeanPostProcessor 创建AOP Bean后置处理器

func (*AopBeanPostProcessor) Disable

func (p *AopBeanPostProcessor) Disable()

Disable 禁用处理器

func (*AopBeanPostProcessor) Enable

func (p *AopBeanPostProcessor) Enable()

Enable 启用处理器

func (*AopBeanPostProcessor) IsEnabled

func (p *AopBeanPostProcessor) IsEnabled() bool

IsEnabled 检查是否启用

func (*AopBeanPostProcessor) ProcessBean

func (p *AopBeanPostProcessor) ProcessBean(beanID string, bean any) any

ProcessBean 处理Bean

type AopBeanScanner

type AopBeanScanner struct {
	// contains filtered or unexported fields
}

AopBeanScanner AOP Bean扫描器

扫描并注册带有AOP注解的Bean

func NewAopBeanScanner

func NewAopBeanScanner(container *AopContainer) *AopBeanScanner

NewAopBeanScanner 创建AOP Bean扫描器

func (*AopBeanScanner) Disable

func (s *AopBeanScanner) Disable()

Disable 禁用扫描器

func (*AopBeanScanner) Enable

func (s *AopBeanScanner) Enable()

Enable 启用扫描器

func (*AopBeanScanner) GetContainer

func (s *AopBeanScanner) GetContainer() *AopContainer

GetContainer 获取容器

func (*AopBeanScanner) IsEnabled

func (s *AopBeanScanner) IsEnabled() bool

IsEnabled 检查是否启用

func (*AopBeanScanner) Scan

func (s *AopBeanScanner) Scan(basePath string) error

Scan 扫描指定路径

type AopConfig

type AopConfig struct {
	Mode        AopMode // AOP 模式
	Weaver      Weaver  // 织入器
	EnableCache bool    // 是否启用代理缓存
}

AopConfig AOP 配置。

func ConfigureAopManager

func ConfigureAopManager() *AopConfig

ConfigureAopManager 配置AOP管理器

根据构建标签自动配置最优的AOP模式

func DefaultAopConfig

func DefaultAopConfig() *AopConfig

DefaultAopConfig 创建默认AOP配置。

type AopContainer

type AopContainer struct {
	core.Container
	// contains filtered or unexported fields
}

AopContainer AOP 容器。

集成 AOP 功能的 IoC 容器。

func CreateAopContainer

func CreateAopContainer() *AopContainer

CreateAopContainer 创建AOP容器的便捷函数

func CreateAopContainerWithConfig

func CreateAopContainerWithConfig(config *AopConfig) *AopContainer

CreateAopContainerWithConfig 创建AOP容器(指定配置)

func NewAopContainer

func NewAopContainer(baseContainer core.Container) *AopContainer

NewAopContainer 创建AOP容器。

func (*AopContainer) DisableAop

func (c *AopContainer) DisableAop()

DisableAop 禁用AOP

func (*AopContainer) EnableAop

func (c *AopContainer) EnableAop()

EnableAop 启用AOP

func (*AopContainer) GetAspects

func (c *AopContainer) GetAspects() []*AspectMeta

GetAspects 获取所有切面

func (*AopContainer) GetFactory

func (c *AopContainer) GetFactory() *AopBeanFactory

GetFactory 获取Bean工厂

func (*AopContainer) GetIntegration

func (c *AopContainer) GetIntegration() *AopIntegration

GetIntegration 获取AOP集成器

func (*AopContainer) GetProcessor

func (c *AopContainer) GetProcessor() *AopBeanPostProcessor

GetProcessor 获取后置处理器

func (*AopContainer) IsAopEnabled

func (c *AopContainer) IsAopEnabled() bool

IsAopEnabled 检查AOP是否启用

func (*AopContainer) RegisterAopBean

func (c *AopContainer) RegisterAopBean(beanDef *AopBeanDefinition, target any) error

RegisterAopBean 注册AOP Bean

func (*AopContainer) RegisterAopBeanWithAspects

func (c *AopContainer) RegisterAopBeanWithAspects(beanID string, beanType reflect.Type, target any, aspects ...*AspectMeta) error

RegisterAopBeanWithAspects 注册AOP Bean(带切面)

func (*AopContainer) RegisterAopBeanWithID

func (c *AopContainer) RegisterAopBeanWithID(beanID string, beanType reflect.Type, target any) error

RegisterAopBeanWithID 注册AOP Bean(指定ID)

func (*AopContainer) RegisterAspect

func (c *AopContainer) RegisterAspect(aspect *AspectMeta)

RegisterAspect 注册切面

func (*AopContainer) RegisterAspects

func (c *AopContainer) RegisterAspects(aspects ...*AspectMeta)

RegisterAspects 批量注册切面

type AopContainerBuilder

type AopContainerBuilder struct {
	// contains filtered or unexported fields
}

AopContainerBuilder AOP容器构建器

提供流式API构建AOP容器

func NewAopContainerBuilder

func NewAopContainerBuilder() *AopContainerBuilder

NewAopContainerBuilder 创建AOP容器构建器

func (*AopContainerBuilder) Build

func (b *AopContainerBuilder) Build() (*AopContainer, error)

Build 构建AOP容器

func (*AopContainerBuilder) BuildOrPanic

func (b *AopContainerBuilder) BuildOrPanic() *AopContainer

BuildOrPanic 构建AOP容器(失败时panic)

func (*AopContainerBuilder) WithAopMode

func (b *AopContainerBuilder) WithAopMode(mode AopMode) *AopContainerBuilder

WithAopMode 设置AOP模式

func (*AopContainerBuilder) WithAspect

func (b *AopContainerBuilder) WithAspect(aspect *AspectMeta) *AopContainerBuilder

WithAspect 添加切面

func (*AopContainerBuilder) WithAspects

func (b *AopContainerBuilder) WithAspects(aspects ...*AspectMeta) *AopContainerBuilder

WithAspects 批量添加切面

func (*AopContainerBuilder) WithBaseContainer

func (b *AopContainerBuilder) WithBaseContainer(container core.Container) *AopContainerBuilder

WithBaseContainer 设置基础容器

func (*AopContainerBuilder) WithBean

WithBean 添加Bean

func (*AopContainerBuilder) WithBeanWithAspects

func (b *AopContainerBuilder) WithBeanWithAspects(beanID string, beanType reflect.Type, target any, aspects ...*AspectMeta) *AopContainerBuilder

WithBeanWithAspects 添加Bean(带切面)

func (*AopContainerBuilder) WithBeanWithID

func (b *AopContainerBuilder) WithBeanWithID(beanID string, beanType reflect.Type, target any) *AopContainerBuilder

WithBeanWithID 添加Bean(指定ID)

func (*AopContainerBuilder) WithConfig

func (b *AopContainerBuilder) WithConfig(config *AopConfig) *AopContainerBuilder

WithConfig 设置配置

type AopIntegration

type AopIntegration struct {
	// contains filtered or unexported fields
}

AopIntegration AOP集成器

提供代码生成和运行时AOP的统一集成

func NewAopIntegration

func NewAopIntegration(config *AopConfig) *AopIntegration

NewAopIntegration 创建AOP集成器

func (*AopIntegration) CreateProxy

func (i *AopIntegration) CreateProxy(beanID string, target any) any

CreateProxy 创建代理对象

func (*AopIntegration) GetAspects

func (i *AopIntegration) GetAspects() []*AspectMeta

GetAspects 获取所有切面

func (*AopIntegration) GetManager

func (i *AopIntegration) GetManager() *AopManager

GetManager 获取AOP管理器

func (*AopIntegration) GetMetadataExtractor

func (i *AopIntegration) GetMetadataExtractor() *AspectMetadataExtractor

GetMetadataExtractor 获取元数据提取器

func (*AopIntegration) GetProxyFactory

func (i *AopIntegration) GetProxyFactory() *GeneratedProxyFactory

GetProxyFactory 获取代理工厂

func (*AopIntegration) GetScannedProxy

func (i *AopIntegration) GetScannedProxy(typeName string) (string, bool)

GetScannedProxy 获取扫描到的代理类型文件路径

func (*AopIntegration) RegisterAspect

func (i *AopIntegration) RegisterAspect(aspect *AspectMeta)

RegisterAspect 注册切面

func (*AopIntegration) RegisterAspects

func (i *AopIntegration) RegisterAspects(aspects ...*AspectMeta)

RegisterAspects 批量注册切面

func (*AopIntegration) RegisterProxyType

func (i *AopIntegration) RegisterProxyType(typeName string, filePath string)

RegisterProxyType 注册代理类型(供扫描器使用)

type AopManager

type AopManager struct {
	// contains filtered or unexported fields
}

AopManager AOP 管理器。

func (*AopManager) GetAspects

func (m *AopManager) GetAspects() []*AspectMeta

GetAspects 获取所有切面

func (*AopManager) MatchAspectsForType

func (m *AopManager) MatchAspectsForType(beanType any) []*AspectMeta

MatchAspectsForType 匹配指定类型的切面

func (*AopManager) RegisterAspect

func (m *AopManager) RegisterAspect(aspect *AspectMeta)

RegisterAspect 注册切面

func (*AopManager) RegisterAspects

func (m *AopManager) RegisterAspects(aspects ...*AspectMeta)

RegisterAspects 批量注册切面

type AopMetrics

type AopMetrics struct {
	TotalProxies       atomic.Int64
	GeneratedProxies   atomic.Int64
	RuntimeProxies     atomic.Int64
	TotalAspects       atomic.Int64
	TotalInterceptions atomic.Int64
	// contains filtered or unexported fields
}

AopMetrics AOP指标

收集AOP相关的性能指标 使用 atomic 操作优化高并发场景下的计数性能

func NewAopMetrics

func NewAopMetrics() *AopMetrics

NewAopMetrics 创建AOP指标

func (*AopMetrics) GetMetrics

func (m *AopMetrics) GetMetrics() map[string]any

GetMetrics 获取指标

func (*AopMetrics) RecordAspectRegistered

func (m *AopMetrics) RecordAspectRegistered()

RecordAspectRegistered 记录切面注册

func (*AopMetrics) RecordInterception

func (m *AopMetrics) RecordInterception(latency float64)

RecordInterception 记录拦截

func (*AopMetrics) RecordProxyCreated

func (m *AopMetrics) RecordProxyCreated(isGenerated bool)

RecordProxyCreated 记录代理创建

func (*AopMetrics) Reset

func (m *AopMetrics) Reset()

Reset 重置指标

type AopMode

type AopMode string

AopMode AOP 模式枚举。

const (
	// AopModeRuntime 运行时模式,使用反射和动态代理。
	AopModeRuntime AopMode = "runtime"

	// AopModeGenerated 代码生成模式,使用编译时代码生成。
	AopModeGenerated AopMode = "generated"

	// AopModeMixed 混合模式,自动选择最优方案。
	AopModeMixed AopMode = "mixed"
)

func DetectOptimalMode

func DetectOptimalMode() AopMode

DetectOptimalMode 检测最优AOP模式

type AopRegistry

type AopRegistry struct {
	// contains filtered or unexported fields
}

AopRegistry AOP 注册表

管理所有切面和织入器的注册中心。 用于在 IoC 容器中集成 AOP 功能。

func NewAopRegistry

func NewAopRegistry() *AopRegistry

NewAopRegistry 创建 AOP 注册表

返回值:

  • *AopRegistry: 注册表实例

func (*AopRegistry) GetAspects

func (r *AopRegistry) GetAspects() []*AspectMeta

GetAspects 获取所有切面

func (*AopRegistry) GetWeaver

func (r *AopRegistry) GetWeaver(beanID string) (Weaver, bool)

GetWeaver 获取织入器

func (*AopRegistry) MatchAspectsForType

func (r *AopRegistry) MatchAspectsForType(t reflect.Type) []*AspectMeta

MatchAspectsForType 为类型匹配切面

根据类型匹配所有适用的切面,并按 Order 排序。

func (*AopRegistry) RegisterAspect

func (r *AopRegistry) RegisterAspect(aspect *AspectMeta)

RegisterAspect 注册切面

func (*AopRegistry) RegisterWeaver

func (r *AopRegistry) RegisterWeaver(beanID string, weaver Weaver)

RegisterWeaver 注册织入器

func (*AopRegistry) WeaveIfNeeded

func (r *AopRegistry) WeaveIfNeeded(beanID string, target any) any

WeaveIfNeeded 按需织入

如果指定 beanID 有对应的织入器,则织入目标对象。

type AroundFunc

type AroundFunc func(originalFunc func(args ...any) []any, args ...any) []any

AroundFunc 环绕函数类型,完全控制原函数的执行。

参数:

  • originalFunc: 被装饰的原始函数,接受 []any 参数并返回 []any 结果
  • args: 原始函数的参数

返回值:

  • []any: 最终的结果,由 around 函数决定是否调用 originalFunc 以及如何处理结果

type AspectBuilder

type AspectBuilder struct {
	// contains filtered or unexported fields
}

AspectBuilder 切面构建器

提供流式API构建切面

func NewAspectBuilder

func NewAspectBuilder() *AspectBuilder

NewAspectBuilder 创建切面构建器

func (*AspectBuilder) Advice

func (b *AspectBuilder) Advice(advice Advice) *AspectBuilder

Advice 设置通知

func (*AspectBuilder) After

func (b *AspectBuilder) After(fn func(JoinPoint)) *AspectBuilder

After 设置后置通知

func (*AspectBuilder) Around

func (b *AspectBuilder) Around(fn func(JoinPoint, ProceedFunc) any) *AspectBuilder

Around 设置环绕通知

func (*AspectBuilder) Before

func (b *AspectBuilder) Before(fn func(JoinPoint)) *AspectBuilder

Before 设置前置通知

func (*AspectBuilder) Build

func (b *AspectBuilder) Build() *AspectMeta

Build 构建切面元数据

func (*AspectBuilder) BuildAndRegister

func (b *AspectBuilder) BuildAndRegister() *AspectMeta

BuildAndRegister 构建并注册切面

func (*AspectBuilder) Instance

func (b *AspectBuilder) Instance(instance any) *AspectBuilder

Instance 设置切面实例

func (*AspectBuilder) MatchAll

func (b *AspectBuilder) MatchAll() *AspectBuilder

MatchAll 设置匹配所有

func (*AspectBuilder) MatchByName

func (b *AspectBuilder) MatchByName(name string) *AspectBuilder

MatchByName 设置按名称匹配的切点

func (*AspectBuilder) MatchByRegex

func (b *AspectBuilder) MatchByRegex(pattern string) *AspectBuilder

MatchByRegex 设置按正则匹配的切点

func (*AspectBuilder) MatchInterface

func (b *AspectBuilder) MatchInterface(iface any) *AspectBuilder

MatchInterface 设置按接口匹配的切点

func (*AspectBuilder) Order

func (b *AspectBuilder) Order(order int) *AspectBuilder

Order 设置执行顺序

func (*AspectBuilder) PointCut

func (b *AspectBuilder) PointCut(pointCut PointCut) *AspectBuilder

PointCut 设置切点

type AspectMeta

type AspectMeta struct {
	Instance any      // 切面实例对象
	PointCut PointCut // 切点定义,匹配目标方法
	Advice   Advice   // 通知,包含增强逻辑
	Order    int      // 执行顺序,数字越小越先执行
}

AspectMeta 切面元数据。

存储切面的实例、切点、通知和执行顺序。 切面是 AOP 的核心数据结构,定义了"在什么地方、做什么增强"。

func CreateAfterAspect

func CreateAfterAspect(methodName string, fn func(JoinPoint), order int) *AspectMeta

CreateAfterAspect 创建后置切面的便捷函数

func CreateAroundAspect

func CreateAroundAspect(methodName string, fn func(JoinPoint, ProceedFunc) any, order int) *AspectMeta

CreateAroundAspect 创建环绕切面的便捷函数

func CreateAspect

func CreateAspect(pointCut PointCut, advice Advice, order int) *AspectMeta

CreateAspect 创建切面的便捷函数

func CreateAspectFromTarget

func CreateAspectFromTarget(target string, advice Advice, order int) (*AspectMeta, error)

CreateAspectFromTarget 从目标字符串创建切面

func CreateBeforeAspect

func CreateBeforeAspect(methodName string, fn func(JoinPoint), order int) *AspectMeta

CreateBeforeAspect 创建前置切面的便捷函数

func GetGlobalAspects

func GetGlobalAspects() []*AspectMeta

GetGlobalAspects 获取全局切面

type AspectMetadataExtractor

type AspectMetadataExtractor struct{}

AspectMetadataExtractor 切面元数据提取器

从代码生成的代理中提取切面元数据

func NewAspectMetadataExtractor

func NewAspectMetadataExtractor() *AspectMetadataExtractor

NewAspectMetadataExtractor 创建切面元数据提取器

func (*AspectMetadataExtractor) Extract

func (e *AspectMetadataExtractor) Extract(proxyType reflect.Type) []*AspectMeta

Extract 从代理类型提取切面元数据

func (*AspectMetadataExtractor) ExtractFromBeanID

func (e *AspectMetadataExtractor) ExtractFromBeanID(beanID string) []*AspectMeta

ExtractFromBeanID 从bean ID提取切面元数据

type BuildTagChecker

type BuildTagChecker struct{}

BuildTagChecker 构建标签检查器

检查当前构建是否包含特定标签

func NewBuildTagChecker

func NewBuildTagChecker() *BuildTagChecker

NewBuildTagChecker 创建构建标签检查器

func (*BuildTagChecker) GetOptimalMode

func (c *BuildTagChecker) GetOptimalMode() AopMode

GetOptimalMode 获取最优模式

func (*BuildTagChecker) HasTag

func (c *BuildTagChecker) HasTag(tag string) bool

HasTag 检查是否有指定标签

func (*BuildTagChecker) IsGeneratedMode

func (c *BuildTagChecker) IsGeneratedMode() bool

IsGeneratedMode 检查是否为代码生成模式

func (*BuildTagChecker) IsRuntimeMode

func (c *BuildTagChecker) IsRuntimeMode() bool

IsRuntimeMode 检查是否为运行时模式

type ChainExecutor

type ChainExecutor interface {
	// Execute 执行通知链。
	//
	// 参数:
	//   - inv: 调用信息
	//   - aspects: 切面元数据列表
	//   - targetFunc: 目标方法调用函数
	//
	// 返回值:
	//   - any: 方法执行结果
	Execute(inv Invocation, aspects []*AspectMeta, targetFunc func(...any) any) any
}

ChainExecutor 通知链执行器接口。

定义通知链的执行策略。默认实现支持 panic 恢复、自定义拦截器和 context 传播。 可通过实现此接口自定义执行策略(如异步执行、限流等)。

func DefaultChainExecutor

func DefaultChainExecutor() ChainExecutor

DefaultChainExecutor 获取默认通知链执行器

func NewChainExecutor

func NewChainExecutor(opts ...ChainExecutorOption) ChainExecutor

NewChainExecutor 创建通知链执行器

默认启用 panic 恢复。可通过选项自定义行为。

示例:

executor := aop.NewChainExecutor(
    aop.WithInterceptor(tracingInterceptor),
    aop.WithInterceptor(metricsInterceptor),
)
aop.SetDefaultChainExecutor(executor)

type ChainExecutorOption

type ChainExecutorOption func(*chainExecutorConfig)

ChainExecutorOption 执行器选项函数。

用于通过函数式选项模式配置 ChainExecutor。

func WithInterceptor

func WithInterceptor(i Interceptor) ChainExecutorOption

WithInterceptor 添加自定义拦截器。

拦截器按添加顺序嵌套:第一个添加的拦截器在最外层。 拦截器可以修改调用信息、观察结果、处理 panic 等。

func WithRecovery

func WithRecovery() ChainExecutorOption

WithRecovery 启用 panic 恢复。

启用后,目标方法的 panic 会被捕获, afterThrowing 通知会正常执行,然后重新抛出 panic。

type ChainStats

type ChainStats struct {
	TotalExecutions   atomic.Int64 // 总执行次数
	TotalPanics       atomic.Int64 // 总 panic 次数
	TotalInterceptors atomic.Int64 // 总拦截器调用次数
}

ChainStats 通知链统计信息

用于收集通知链执行的运行时统计,所有字段均为原子操作,并发安全。

字段说明:

  • TotalExecutions: 总执行次数
  • TotalPanics: 总 panic 次数
  • TotalInterceptors: 总拦截器调用次数
var GlobalChainStats ChainStats

GlobalChainStats 全局通知链统计

type ClassMatcher

type ClassMatcher func(reflect.Type) bool

ClassMatcher 类匹配器类型

函数类型,接收一个反射类型,返回是否匹配。 用于定义切点的类级别匹配规则。

type GeneratedProxyFactory

type GeneratedProxyFactory struct {
	// contains filtered or unexported fields
}

GeneratedProxyFactory 代码生成代理工厂

创建代码生成的代理对象

func NewGeneratedProxyFactory

func NewGeneratedProxyFactory() *GeneratedProxyFactory

NewGeneratedProxyFactory 创建代码生成代理工厂

func (*GeneratedProxyFactory) Create

func (f *GeneratedProxyFactory) Create(beanID string, target any) (any, error)

Create 创建代理对象

func (*GeneratedProxyFactory) CreateOrFallback

func (f *GeneratedProxyFactory) CreateOrFallback(beanID string, target any, fallback Weaver) any

CreateOrFallback 创建代理或回退到运行时代理

type GeneratedProxyRegistry

type GeneratedProxyRegistry struct {
	// contains filtered or unexported fields
}

GeneratedProxyRegistry 代码生成代理注册表

管理代码生成的代理对象,提供查找和获取功能

func NewGeneratedProxyRegistry

func NewGeneratedProxyRegistry() *GeneratedProxyRegistry

NewGeneratedProxyRegistry 创建代码生成代理注册表

func (*GeneratedProxyRegistry) Clear

func (r *GeneratedProxyRegistry) Clear()

Clear 清空注册表

func (*GeneratedProxyRegistry) Get

func (r *GeneratedProxyRegistry) Get(beanID string) (reflect.Type, bool)

Get 获取代理类型

func (*GeneratedProxyRegistry) Has

func (r *GeneratedProxyRegistry) Has(beanID string) bool

Has 检查是否存在代理

func (*GeneratedProxyRegistry) List

func (r *GeneratedProxyRegistry) List() []string

List 列出所有注册的bean ID

func (*GeneratedProxyRegistry) Register

func (r *GeneratedProxyRegistry) Register(beanID string, proxyType reflect.Type)

Register 注册代理类型

type Interceptor

type Interceptor func(inv Invocation, next func(Invocation) any) any

Interceptor 拦截器函数类型。

在通知链执行前后提供额外的处理逻辑,采用中间件模式。 inv 为当前调用信息,next 为下一个处理函数。

示例:

aop.WithInterceptor(func(inv aop.Invocation, next func(aop.Invocation) any) any {
    start := time.Now()
    result := next(inv)
    slog.Info("method called", "name", inv.Signature().Name(), "duration", time.Since(start))
    return result
})

type InterfaceProxyWrapper

type InterfaceProxyWrapper struct {
	// contains filtered or unexported fields
}

InterfaceProxyWrapper 接口代理包装器(实现 doc.go 中定义的结构体)。

通过反射转发所有接口方法调用,支持 AOP 切面织入。 由于 Go 运行时无法动态替换接口方法,此包装器提供显式的 Invoke/InvokeContext 方法。

使用方式:

wrapper := aop.NewInterfaceProxyWrapper(target, advisors, iface)
result, err := wrapper.InvokeContext(ctx, "MethodName", arg1, arg2)

设计模式: Proxy

func NewInterfaceProxyWrapper

func NewInterfaceProxyWrapper(target any, advisors []*AspectMeta, iface reflect.Type) *InterfaceProxyWrapper

NewInterfaceProxyWrapper 创建接口代理包装器。

func (*InterfaceProxyWrapper) GetAdvisors

func (w *InterfaceProxyWrapper) GetAdvisors() []*AspectMeta

GetAdvisors 获取切面列表

func (*InterfaceProxyWrapper) GetTarget

func (w *InterfaceProxyWrapper) GetTarget() any

GetTarget 获取原始目标对象

func (*InterfaceProxyWrapper) Invoke

func (w *InterfaceProxyWrapper) Invoke(methodName string, args ...any) (any, error)

Invoke 调用接口方法

func (*InterfaceProxyWrapper) InvokeContext

func (w *InterfaceProxyWrapper) InvokeContext(ctx context.Context, methodName string, args ...any) (any, error)

InvokeContext 带上下文的方法调用

func (*InterfaceProxyWrapper) SetExecutor

func (w *InterfaceProxyWrapper) SetExecutor(executor ChainExecutor)

SetExecutor 设置通知链执行器

type InvalidTargetFormatError

type InvalidTargetFormatError struct {
	// contains filtered or unexported fields
}

InvalidTargetFormatError 无效目标格式错误

func (*InvalidTargetFormatError) Error

func (e *InvalidTargetFormatError) Error() string

type Invocation

type Invocation interface {
	JoinPoint

	// Proceed 继续执行。
	//
	// 调用此方法可以执行目标方法或通知链中的下一个通知。
	// 可以传递自定义参数,这些参数会传递给下游的调用。
	Proceed(args ...any) any

	// SetContext 设置调用上下文。
	SetContext(ctx context.Context)
}

Invocation 调用信息接口。

继承自 JoinPoint,并添加了 Proceed 方法。 用于在 Around 通知中控制方法的执行流程。

type JoinPoint

type JoinPoint interface {
	// Method 获取被拦截的方法。
	Method() any

	// Args 获取方法调用时的参数。
	Args() []any

	// Signature 获取方法签名。
	Signature() MethodSignature

	// This 获取代理对象。
	This() any

	// Target 获取目标对象。
	Target() any

	// Context 获取调用上下文。
	Context() context.Context
}

JoinPoint 连接点接口。

AOP 核心概念,代表程序执行的某个位置。在 enhance AOP 框架中, 连接点通常指方法调用,通知(Advice)可以通过 JoinPoint 访问方法调用的上下文。

type MethodInvocation

type MethodInvocation struct {
	MethodName string          // 方法名称
	Func       any             // 目标方法(函数值)
	Params     []any           // 方法调用参数列表
	Object     any             // 目标对象(被代理的原始对象)
	Proxy      any             // 代理对象本身,未设置时 This() 返回 nil
	Ctx        context.Context // 上下文信息,未设置时 Context() 返回 context.Background()
	// contains filtered or unexported fields
}

MethodInvocation 方法调用信息。

用于代码生成的代理类,包含方法调用所需的所有信息。 新增字段 Proxy、Ctx 可按需设置,未设置时保持零值兼容。

func (*MethodInvocation) Args

func (m *MethodInvocation) Args() []any

Args 获取参数

func (*MethodInvocation) Context

func (m *MethodInvocation) Context() context.Context

Context 获取上下文

如果已设置上下文,则返回该上下文;否则返回 context.Background()。

func (*MethodInvocation) Method

func (m *MethodInvocation) Method() any

Method 获取方法。

func (*MethodInvocation) Proceed

func (m *MethodInvocation) Proceed(args ...any) any

Proceed 继续执行

如果已通过 SetProceed 设置了执行函数,则调用它; 否则通过反射调用目标方法。

func (*MethodInvocation) SetContext

func (m *MethodInvocation) SetContext(ctx context.Context)

SetContext 设置上下文

设置后,后续通知链中的 JoinPoint.Context() 将返回新的上下文。

func (*MethodInvocation) SetProceed

func (m *MethodInvocation) SetProceed(p ProceedFunc)

SetProceed 设置继续执行函数

在Around通知中,用于设置继续执行目标方法或下一个通知的函数。

func (*MethodInvocation) Signature

func (m *MethodInvocation) Signature() MethodSignature

Signature 获取方法签名

func (*MethodInvocation) Target

func (m *MethodInvocation) Target() any

Target 获取目标对象

func (*MethodInvocation) This

func (m *MethodInvocation) This() any

This 获取代理对象

type MethodMatcher

type MethodMatcher func(reflect.Method) bool

MethodMatcher 方法匹配器类型

函数类型,接收一个反射方法,返回是否匹配。 用于定义切点的方法级别匹配规则。

type MethodSignature

type MethodSignature interface {
	// Name 获取方法名。
	Name() string

	// DeclaringType 获取方法声明的类型。
	DeclaringType() reflect.Type
}

MethodSignature 方法签名接口。

描述方法的元数据信息,包括方法名和声明类型。

func NewMethodSignature

func NewMethodSignature(name string, t reflect.Type) MethodSignature

NewMethodSignature 创建方法签名。

参数:

  • name: 方法名
  • t: 方法声明的类型

返回值:

  • MethodSignature: 方法签名实例

type PanicInfo

type PanicInfo struct {
	Value any    // panic 的原始值
	Stack []byte // 堆栈信息
}

PanicInfo 包含 panic 信息和堆栈

func (*PanicInfo) Error

func (p *PanicInfo) Error() string

Error 实现 error 接口

type PointCut

type PointCut interface {
	// MatchClass 匹配类。
	//
	// 检查给定类型是否匹配切点条件。
	// 如果返回 true,表示该类型的所有方法都可能被拦截(还需通过方法匹配)。
	// 如果返回 false,则该类型的所有方法都不会被拦截。
	MatchClass(c reflect.Type) bool

	// MatchMethod 匹配方法。
	//
	// 检查给定方法是否匹配切点条件。
	// 只有匹配的方法才会被代理拦截。
	MatchMethod(m reflect.Method) bool

	// String 返回切点的字符串表示。
	//
	// 用于调试和日志输出,返回切点的类型和匹配规则。
	String() string
}

PointCut 切点接口。

定义 AOP 中用于匹配目标方法的规则。切点决定了哪些类或方法需要被拦截, 是 AOP 框架的核心组件之一。

匹配流程:

  1. 调用 MatchClass 检查目标类型是否匹配(如果类匹配器存在)
  2. 调用 MatchMethod 检查目标方法是否匹配(如果方法匹配器存在)
  3. 如果都匹配(或对应匹配器为 nil),则该方法会被拦截

func Compose

func Compose(pointcuts ...PointCut) PointCut

Compose 组合多个切点(AND 逻辑)

只有当所有切点都匹配时,才认为匹配。

参数:

  • pointcuts: 切点列表

返回值:

  • PointCut: 组合后的切点

示例:

// 匹配 Service 类中以 Get 开头的方法
aop.Compose(
    aop.MatchByClassName("*Service"),
    aop.MatchByNamePrefix("Get"),
)

func ComposeOr

func ComposeOr(pointcuts ...PointCut) PointCut

ComposeOr 组合多个切点(OR 逻辑)

只要有一个切点匹配,就认为匹配。

参数:

  • pointcuts: 切点列表

返回值:

  • PointCut: 组合后的切点

示例:

// 匹配 GetUser 或 UpdateUser 方法
aop.ComposeOr(
    aop.MatchByName("GetUser"),
    aop.MatchByName("UpdateUser"),
)

func MatchAll

func MatchAll() PointCut

MatchAll 匹配所有

返回匹配所有类和方法的切点。

返回值:

  • PointCut: 匹配所有目标的切点

示例:

// 拦截所有方法
aop.MatchAll()

func MatchByAnnotation

func MatchByAnnotation(annotationType reflect.Type) PointCut

MatchByAnnotation 按注解类型匹配

匹配带有指定注解类型的方法。

参数:

  • annotationType: 注解类型

返回值:

  • PointCut: 匹配带注解方法的切点

注意:

  • 此方法通过方法名前缀来匹配

func MatchByClassName

func MatchByClassName(className string) PointCut

MatchByClassName 按类名匹配

匹配指定类名的所有方法。

参数:

  • className: 类名(支持通配符 *)

返回值:

  • PointCut: 匹配指定类名的切点

示例:

// 匹配所有 Service 结尾的类
aop.MatchByClassName("*Service")

// 精确匹配 UserService 类
aop.MatchByClassName("UserService")

func MatchByMethodSignature

func MatchByMethodSignature(methodName string, paramTypes ...reflect.Type) PointCut

MatchByMethodSignature 按方法签名匹配

匹配具有指定方法签名的方法(方法名 + 参数类型)。 这是最精确的匹配方式,类似 Spring 的 execution 表达式。

参数:

  • methodName: 方法名
  • paramTypes: 参数类型列表(可选,nil 表示只匹配方法名)

返回值:

  • PointCut: 匹配指定方法签名的切点

示例:

// 精确匹配 GetUser(id int64) 方法
aop.MatchByMethodSignature("GetUser", reflect.TypeOf(int64(0)))

// 匹配所有名为 Save 的方法(不限参数)
aop.MatchByMethodSignature("Save", nil)

func MatchByName

func MatchByName(name string) PointCut

MatchByName 按方法名匹配

匹配指定名称的方法。

参数:

  • name: 方法名

返回值:

  • PointCut: 匹配指定方法名的切点

示例:

// 只拦截 DoSomething 方法
aop.MatchByName("DoSomething")

func MatchByNamePrefix

func MatchByNamePrefix(prefix string) PointCut

MatchByNamePrefix 按方法名前缀匹配

匹配指定前缀的方法。

参数:

  • prefix: 方法名前缀

返回值:

  • PointCut: 匹配指定前缀的切点

示例:

// 拦截所有以 Do 开头的方法
aop.MatchByNamePrefix("Do")

func MatchByPackage

func MatchByPackage(packagePath string) PointCut

MatchByPackage 按包路径匹配

匹配指定包路径下的所有类和方法。

参数:

  • packagePath: 包路径前缀(如 "github.com/myapp/service")

返回值:

  • PointCut: 匹配指定包的切点

示例:

// 拦截 service 包下的所有方法
aop.MatchByPackage("github.com/myapp/service")

func MatchByRegex

func MatchByRegex(pattern string) PointCut

MatchByRegex 按正则表达式匹配

匹配符合正则表达式的方法名。

参数:

  • pattern: 正则表达式

返回值:

  • PointCut: 匹配正则表达式的切点

示例:

// 拦截所有以 do 或 Do 开头的方法
aop.MatchByRegex("(?i)^do.*")

func MatchByReturnType

func MatchByReturnType(returnType reflect.Type) PointCut

MatchByReturnType 按返回值类型匹配

匹配返回指定类型的方法。

参数:

  • returnType: 返回值类型

返回值:

  • PointCut: 匹配指定返回值类型的切点

示例:

// 匹配所有返回 error 的方法
aop.MatchByReturnType(reflect.TypeOf((*error)(nil)).Elem())

func MatchClass

func MatchClass(matcher ClassMatcher) PointCut

MatchClass 匹配类

返回只匹配类的切点,不匹配具体方法。

参数:

  • matcher: 类匹配函数

返回值:

  • PointCut: 匹配给定类的切点

示例:

aop.MatchClass(func(t reflect.Type) bool {
    return t.Name() == "UserService"
})

func MatchClassMethod

func MatchClassMethod(classMatcher ClassMatcher, methodMatcher MethodMatcher) PointCut

MatchClassMethod 匹配类和方法的组合切点

同时指定类和方法匹配条件。

参数:

  • classMatcher: 类匹配函数
  • methodMatcher: 方法匹配函数

返回值:

  • PointCut: 组合切点

func MatchInterface

func MatchInterface(y any) PointCut

MatchInterface 按接口类型匹配

匹配实现了指定接口的类型。

参数:

  • y: 接口类型,传入接口变量即可

返回值:

  • PointCut: 匹配实现接口的类的切点

示例:

// 拦截所有实现 ServiceInterface 接口的类
aop.MatchInterface((*ServiceInterface)(nil))

func MatchMethod

func MatchMethod(matcher MethodMatcher) PointCut

MatchMethod 匹配方法

返回只匹配方法的切点,不匹配具体类。

参数:

  • matcher: 方法匹配函数

返回值:

  • PointCut: 匹配给定方法的切点

示例:

aop.MatchMethod(func(m reflect.Method) bool {
    return m.Name == "DoSomething"
})

type PointCutFunc

type PointCutFunc func(reflect.Method) bool

PointCutFunc 函数式切点适配器

Go 惯用法:使用函数类型替代接口实现,符合 Go 标准库中 http.HandlerFunc 的设计模式。 将函数适配为 PointCut 接口,仅匹配方法(类匹配始终返回 true)。

func (PointCutFunc) MatchClass

func (f PointCutFunc) MatchClass(c reflect.Type) bool

MatchClass 实现 PointCut 接口(始终返回 true)

func (PointCutFunc) MatchMethod

func (f PointCutFunc) MatchMethod(m reflect.Method) bool

MatchMethod 实现 PointCut 接口

func (PointCutFunc) String

func (f PointCutFunc) String() string

String 实现 PointCut 接口

type PointCutWithClass

type PointCutWithClass struct {
	Class ClassMatcher
	Match MethodMatcher
}

PointCutWithClass 带类匹配的函数式切点

同时支持类和方法匹配的函数式切点适配器。 当需要同时指定类和方法匹配规则时使用。

func (PointCutWithClass) MatchClass

func (p PointCutWithClass) MatchClass(c reflect.Type) bool

MatchClass 实现 PointCut 接口

func (PointCutWithClass) MatchMethod

func (p PointCutWithClass) MatchMethod(m reflect.Method) bool

MatchMethod 实现 PointCut 接口

func (PointCutWithClass) String

func (p PointCutWithClass) String() string

String 实现 PointCut 接口

type ProceedFunc

type ProceedFunc func(args ...any) any

ProceedFunc 继续执行函数类型。

在 Around 通知中,调用此函数可以继续执行目标方法或下一个通知。 参数为传递给目标方法的参数,返回值为目标方法的返回值。

type ProxyFactory

type ProxyFactory struct {
	// contains filtered or unexported fields
}

ProxyFactory 代理工厂(实现 doc.go 中定义的结构体)。

负责创建 AOP 代理对象。根据目标对象的类型(接口或结构体),创建相应的代理。

使用示例:

factory := aop.NewProxyFactory(&UserService{})
factory.SetAspects(aspects)
proxy := factory.GetProxy()

func NewProxyFactory

func NewProxyFactory(target any) *ProxyFactory

NewProxyFactory 创建代理工厂

参数:

  • target: 目标对象,可以是结构体指针或接口实现

返回值:

  • *ProxyFactory: 代理工厂实例

示例:

factory := aop.NewProxyFactory(&UserService{})

func (*ProxyFactory) GetProxy

func (p *ProxyFactory) GetProxy() any

GetProxy 获取代理对象

根据目标对象的类型,创建并返回代理对象。 如果没有匹配的切面,则返回原对象。

返回值:

  • any: 代理对象或原对象

func (*ProxyFactory) SetAspects

func (p *ProxyFactory) SetAspects(aspects []*AspectMeta)

SetAspects 设置切面

参数:

  • aspects: 切面元数据列表

func (*ProxyFactory) SetExecutor

func (p *ProxyFactory) SetExecutor(executor ChainExecutor)

SetExecutor 设置通知链执行器

设置后,由此工厂创建的 ReflectiveAopProxy 将使用指定的执行器。 传入 nil 表示使用全局默认执行器。

type ReflectiveAopProxy

type ReflectiveAopProxy struct {
	// contains filtered or unexported fields
}

ReflectiveAopProxy 基于反射的 AOP 代理。

由于 Go 运行时无法动态替换结构体方法,ReflectiveAopProxy 通过反射 拦截方法调用并执行通知链。用户通过 Call/CallContext 方法调用目标方法, AOP 通知会自动执行。

使用方式:

proxy := weaver.Weave(target).(*aop.ReflectiveAopProxy)
result, err := proxy.Call("MethodName", arg1, arg2)
result, err := proxy.CallContext(ctx, "MethodName", arg1, arg2)

func AsReflectiveProxy

func AsReflectiveProxy(obj any) (*ReflectiveAopProxy, bool)

AsReflectiveProxy 将对象转换为 ReflectiveAopProxy

func (*ReflectiveAopProxy) Call

func (p *ReflectiveAopProxy) Call(methodName string, args ...any) (any, error)

Call 通过反射调用目标方法并执行通知链

func (*ReflectiveAopProxy) CallContext

func (p *ReflectiveAopProxy) CallContext(ctx context.Context, methodName string, args ...any) (any, error)

CallContext 通过反射调用目标方法并执行通知链(带 context)

参数:

  • ctx: 上下文,可通过 JoinPoint.Context() 在通知中获取
  • methodName: 方法名
  • args: 方法参数

返回值:

  • any: 方法返回值(多返回值时返回 []any)
  • error: 调用错误(仅表示方法查找失败,不包含目标方法的 panic)

func (*ReflectiveAopProxy) MustCall

func (p *ReflectiveAopProxy) MustCall(methodName string, args ...any) any

MustCall 调用目标方法,panic on error

func (*ReflectiveAopProxy) SetExecutor

func (p *ReflectiveAopProxy) SetExecutor(executor ChainExecutor)

SetExecutor 设置通知链执行器

func (*ReflectiveAopProxy) Target

func (p *ReflectiveAopProxy) Target() any

Target 返回原始目标对象。

type Weaver

type Weaver interface {
	// Weave 织入目标对象。
	//
	// 将已注册的切面织入目标对象,返回代理对象。
	//
	// 参数:
	//   - target: 目标对象,可以是结构体指针或接口实现
	//
	// 返回值:
	//   - any: 代理对象(如果匹配到切面)或原对象
	//
	// 注意:
	//   - 返回的对象类型可能和原对象不同(代理类型)
	//   - 使用代理对象调用方法时,匹配的通知会自动执行
	Weave(target any) any

	// AddAspects 添加切面。
	//
	// 添加一个或多个切面到织入器。
	// 添加后,这些切面会应用于后续 Weave 调用。
	//
	// 参数:
	//   - aspects: 一个或多个切面元数据
	AddAspects(aspects ...*AspectMeta)
}

Weaver 织入器接口。

负责将切面织入目标对象,生成代理对象。 类似于 Spring 中的 AopProxyFactory。

工作流程:

  1. 创建织入器: NewWeaver()
  2. 添加切面: AddAspects(aspect1, aspect2, ...)
  3. 织入目标: Weave(target) -> 返回代理对象

织入规则:

  • 如果目标对象没有任何匹配的切面,返回原对象(不进行代理)
  • 如果目标对象有匹配的切面,创建代理对象
  • 代理对象的方法调用会触发匹配的通知

func NewWeaver

func NewWeaver() Weaver

NewWeaver 创建织入器

返回值:

  • Weaver: 织入器实例

示例:

weaver := aop.NewWeaver()
weaver.AddAspects(aspectMeta)
proxy := weaver.Weave(&UserService{})

Directories

Path Synopsis
Package chain 提供 AOP 拦截器链实现,用于 enhance 框架。
Package chain 提供 AOP 拦截器链实现,用于 enhance 框架。
Package generator 提供 AOP 代码生成功能,用于 enhance 框架。
Package generator 提供 AOP 代码生成功能,用于 enhance 框架。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL