context

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 14 Imported by: 0

README

context 包 — 应用上下文

所属层级: Core Layer
设计理念: 运行时核心入口,聚合所有子系统

概述

context 包提供应用上下文(ApplicationContext),聚合了 enhance 框架的四个核心子系统:Container(IoC)、Environment(配置)、Lifecycle(生命周期)、EventBus(事件)。

核心功能
功能 说明
Container IoC 依赖注入容器,管理 Bean 的注册和获取
Environment 分层配置源管理,支持多级配置源
Lifecycle 应用生命周期阶段管理
EventBus 事件发布与订阅
EventPublisher 事件发布器接口,解耦事件发布逻辑

核心接口

ApplicationContext 接口
type ApplicationContext interface {
    Container() core.Container
    Environment() *environment.Environment
    Lifecycle() *life.LifecycleManager
    EventBus() *event.EventBus
    EventPublisher() EventPublisher

    Register(name string, opts ...core.BuilderOption) error
    Get(name string) (any, error)
    Invoke(fn any) error

    Start() error
    Stop() error
    IsRunning() bool
}

// EventPublisher 事件发布器接口
type EventPublisher interface {
    Publish(event event.ApplicationEvent)
}
DefaultApplicationContext
type DefaultApplicationContext struct {
    container core.Container
    env       *environment.Environment
    lifecycle *life.LifecycleManager
    events    *event.EventBus
}
方法说明
方法 说明
Container() 返回 IoC 容器
Environment() 返回环境配置
Lifecycle() 返回生命周期管理器
EventBus() 返回事件总线
EventPublisher() 返回事件发布器接口
Register(name, opts...) 在容器中注册 Bean
Get(name) 从容器中获取指定名称的 Bean
Invoke(fn) 调用函数并自动注入依赖参数
Start() 启动应用,发布启动事件并切换至运行阶段
Stop() 停止应用,切换至停止阶段并发布停止事件
IsRunning() 检查应用是否处于运行状态

快速开始

创建应用上下文
package main

import (
    "fmt"
    "github.com/xudefa/enhance/context"
    "github.com/xudefa/enhance/core"
    "github.com/xudefa/enhance/config/environment"
)

func main() {
    container := core.New()
    env := environment.NewEnvironment()
    ctx := context.NewApplicationContext(container, env)

    // 注册 Bean
    _ = ctx.Register(
        reflect.TypeOf(&MyService{}),
        core.Bean(&MyService{Name: "hello"}),
        core.Singleton(),
    )

    // 获取 Bean
    svc := core.MustGetBean[*MyService](ctx.Container())
    fmt.Println(svc.Name)

    // 启动
    ctx.Start()
    defer ctx.Stop()
}

type MyService struct {
    Name string
}
启动与停止流程
Start() 流程
  1. 发布 EventApplicationStarted
  2. 设置生命周期阶段为 PhaseRunning
  3. 发布 EventApplicationReady
Stop() 流程
  1. 设置生命周期阶段为 PhaseStopping
  2. 设置生命周期阶段为 PhaseStopped
  3. 发布 EventApplicationStopped

API 参考

辅助方法
func (c *DefaultApplicationContext) GetBean(beanID string) (any, bool)
func (c *DefaultApplicationContext) HasProperty(key string) bool
func (c *DefaultApplicationContext) GetProperty(key string) (any, bool)
func (c *DefaultApplicationContext) ClassLoader() interface{ HasClass(name string) bool }
ClassLoader 缓存优化

buildInfoClassLoader 使用 runtime/debug.ReadBuildInfo() 检查模块是否在编译依赖中。

优化策略
  • sync.Once 延迟初始化:首次调用 HasClass 时读取构建信息
  • 依赖列表缓存:将构建信息中的依赖模块列表缓存到内存
  • 全局共享实例:使用 globalClassLoader 全局共享实例
性能提升
  • 首次调用:读取构建信息(约 1-5ms)
  • 后续调用:直接查询缓存(约 10-100ns)
  • 内存开销:每个依赖模块约 50 字节字符串,100 个依赖约 5KB

使用示例

事件订阅
ctx.EventBus().Subscribe(event.EventApplicationStarted, func(e event.ApplicationEvent) {
    fmt.Println("应用已启动,时间:", e.Timestamp())
})

ctx.Start()
生命周期监听
ctx.Lifecycle().AddListener(&myPhaseListener{})

ctx.Start() // 触发 PhaseRunning 变更通知
方法注入
_ = ctx.Invoke(func(svc *MyService) {
    fmt.Println("注入的 service:", svc.Name)
})

四子系统集成关系

┌──────────────────────────────────────────────────────┐
│              DefaultApplicationContext               │
│                                                      │
│  ┌──────────────┐  ┌──────────────────────────────┐  │
│  │   Container  │  │        Environment           │  │
│  │  (core.Cont) │  │  (environment.Environment)   │  │
│  │              │  │                              │  │
│  │  Register()  │  │  GetProperty()               │  │
│  │  Get()       │  │  AddPropertySource()         │  │
│  │  Invoke()    │  │  GetActiveProfiles()         │  │
│  └──────────────┘  └──────────────────────────────┘  │
│                                                      │
│  ┌──────────────┐  ┌──────────────────────────────┐  │
│  │  Lifecycle   │  │          EventBus            │  │
│  │  (life.Man)  │  │      (event.EventBus)        │  │
│  │              │  │                              │  │
│  │  SetPhase()  │  │  Publish()                   │  │
│  │  GetPhase()  │  │  Subscribe()                 │  │
│  │  AddListen() │  │  Unsubscribe()               │  │
│  └──────────────┘  └──────────────────────────────┘  │
└──────────────────────────────────────────────────────┘

与 Boot 的关系

boot.Boot 在内部持有 DefaultApplicationContext 并进行更细粒度的生命周期控制:

  • Boot.Start()PhaseConfiguringPhaseReady 之间插入自动配置执行、启动器配置等步骤
  • DefaultApplicationContext.Start() 仅处理 PhaseRunning 阶段切换和事件发布

DefaultApplicationContext 同时实现了 condition.ConditionContext 所需的辅助方法(GetBeanHasPropertyGetProperty),通过 conditionCtx 适配器供条件系统使用。


最佳实践

1. 使用 ApplicationContext 作为统一入口
// ✅ 推荐:通过上下文访问所有子系统
ctx := context.NewApplicationContext(container, env)
ctx.Container().Get("myService")
ctx.Environment().GetProperty("app.name")
ctx.EventBus().Publish(event)

// ⚠️ 不推荐:直接访问各个子系统
container.Get("myService")
env.GetProperty("app.name")
2. 合理使用事件订阅
// ✅ 推荐:在启动前订阅事件
ctx.EventBus().Subscribe(event.EventApplicationStarted, handler)
ctx.Start()

// ⚠️ 不推荐:在启动后订阅,可能错过事件
ctx.Start()
ctx.EventBus().Subscribe(event.EventApplicationStarted, handler)
3. 使用 ClassLoader 缓存提升性能
// ✅ 推荐:使用全局共享的 ClassLoader
classLoader := context.GlobalClassLoader()
classLoader.HasClass("github.com/some/lib")

// ⚠️ 不推荐:每次创建新的 ClassLoader
classLoader := context.NewBuildInfoClassLoader()

Documentation

Overview

Package context 提供应用上下文管理,用于 enhance 框架。

核心功能

  • 容器管理: 提供 IoC 容器访问,管理 Bean 的注册和获取
  • 环境配置: 提供环境配置访问,支持多级配置源
  • 事件总线: 提供事件发布和订阅,支持优先级和异步
  • 生命周期: 管理应用启动和关闭,控制状态流转
  • 刷新作用域: 支持配置热更新时的 Bean 刷新

使用方式

获取应用上下文:

ctx := boot.NewApplication()
container := ctx.Container()
env := ctx.Environment()

从容器获取 Bean:

service, err := container.Get("myService")

发布事件:

ctx.PublishEvent(event.NewEvent("myEvent"))

设计模式

  • Facade: ApplicationContext 作为框架核心组件的统一入口
  • Adapter: asyncEventPublisherAdapter 适配 event.AsyncPublisher 为 AsyncEventPublisher
  • Singleton: globalClassLoader 全局共享 ClassLoader 实例

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithBean

func WithBean(t reflect.Type, opts ...core.BeanOption) func(*ApplicationContextBuilder)

WithBean 注册Bean的选项函数

func WithContainer

func WithContainer(container core.Container) func(*ApplicationContextBuilder)

WithContainer 设置容器的选项函数

func WithEnvironment

func WithEnvironment(env *environment.Environment) func(*ApplicationContextBuilder)

WithEnvironment 设置环境的选项函数

func WithProfile

func WithProfile(profile string) func(*ApplicationContextBuilder)

WithProfile 添加Profile的选项函数

func WithProfiles

func WithProfiles(profiles ...string) func(*ApplicationContextBuilder)

WithProfiles 批量添加Profiles的选项函数

Types

type ApplicationContext

type ApplicationContext interface {
	// Container 返回 IoC 容器实例。
	Container() core.Container

	// Environment 返回环境配置实例。
	Environment() *environment.Environment

	// Lifecycle 返回生命周期管理器。
	Lifecycle() *lifecycle.LifecycleManager

	// EventBus 返回事件总线访问接口(支持 EventBus 和 EventBusWithOrdering)。
	EventBus() EventBusAccess

	// EventPublisher 返回事件发布器接口(解耦事件发布)。
	EventPublisher() EventPublisher

	// AsyncEventPublisher 返回异步事件发布器接口。
	AsyncEventPublisher() AsyncEventPublisher

	// RefreshScopeManager 返回刷新作用域管理器。
	RefreshScopeManager() *refresh.RefreshScopeManager

	// Start 启动应用:发布启动事件并切换至运行阶段。
	Start() error

	// Stop 停止应用:切换至停止阶段并发布停止事件。
	Stop() error
}

ApplicationContext 应用上下文接口。

作为框架核心组件的统一入口(Facade 模式),聚合对各个子系统的访问。 不重复定义已有方法,通过 Container() 获取 core.Container 来操作 Bean, 通过 Lifecycle() 获取 lifecycle.LifecycleManager 来控制生命周期。

该接口遵循小接口原则,包含以下方法:

  • Container: 获取依赖注入容器
  • Environment: 获取环境配置
  • Lifecycle: 获取生命周期管理器
  • EventBus: 获取事件总线访问
  • EventPublisher: 获取事件发布器
  • AsyncEventPublisher: 获取异步事件发布器
  • RefreshScopeManager: 获取刷新作用域管理器
  • Start: 启动应用,发布生命周期事件
  • Stop: 停止应用,发布生命周期事件

func CreateApplicationContext

func CreateApplicationContext(opts ...func(*ApplicationContextBuilder)) (ApplicationContext, error)

CreateApplicationContext 创建并配置应用上下文的便捷函数

type ApplicationContextBuilder

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

ApplicationContextBuilder 应用上下文构建器,支持链式配置

func NewApplicationContextBuilder

func NewApplicationContextBuilder() *ApplicationContextBuilder

NewApplicationContextBuilder 创建应用上下文构建器

func (*ApplicationContextBuilder) Bean

Bean 注册Bean定义

func (*ApplicationContextBuilder) Build

Build 构建应用上下文

func (*ApplicationContextBuilder) Container

Container 设置IoC容器

func (*ApplicationContextBuilder) Environment

Environment 设置环境配置

func (*ApplicationContextBuilder) EventBus

EventBus 设置事件总线

func (*ApplicationContextBuilder) Lifecycle

Lifecycle 设置生命周期管理器

func (*ApplicationContextBuilder) MustBuild

MustBuild 构建应用上下文,失败则panic

func (*ApplicationContextBuilder) OnApplicationReady

OnApplicationReady 注册应用就绪事件监听器

func (*ApplicationContextBuilder) OnApplicationStarted

func (b *ApplicationContextBuilder) OnApplicationStarted(listener event.EventListener) *ApplicationContextBuilder

OnApplicationStarted 注册应用启动事件监听器

func (*ApplicationContextBuilder) OnApplicationStopped

func (b *ApplicationContextBuilder) OnApplicationStopped(listener event.EventListener) *ApplicationContextBuilder

OnApplicationStopped 注册应用停止事件监听器

func (*ApplicationContextBuilder) Profile

Profile 添加激活的 Profile

func (*ApplicationContextBuilder) Profiles

Profiles 批量添加激活的 Profiles

func (*ApplicationContextBuilder) RefreshScopeManager

RefreshScopeManager 设置刷新作用域管理器

func (*ApplicationContextBuilder) WithEventListener

func (b *ApplicationContextBuilder) WithEventListener(eventType string, listener event.EventListener) *ApplicationContextBuilder

WithEventListener 添加事件监听器

func (*ApplicationContextBuilder) WithPhaseListener

WithPhaseListener 添加阶段监听器

func (*ApplicationContextBuilder) WithRefreshOption

WithRefreshOption 添加刷新配置选项

type ApplicationContextHelper

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

ApplicationContextHelper 应用上下文辅助工具

func NewApplicationContextHelper

func NewApplicationContextHelper(ctx ApplicationContext) *ApplicationContextHelper

NewApplicationContextHelper 创建应用上下文辅助工具

func (*ApplicationContextHelper) GetActiveProfiles

func (h *ApplicationContextHelper) GetActiveProfiles() []string

GetActiveProfiles 获取激活的Profiles

func (*ApplicationContextHelper) GetBeanByType

func (h *ApplicationContextHelper) GetBeanByType(t reflect.Type) (any, error)

GetBeanByType 按类型获取Bean

func (*ApplicationContextHelper) GetBeanByTypeOrDefault

func (h *ApplicationContextHelper) GetBeanByTypeOrDefault(t reflect.Type, defaultVal any) any

GetBeanByTypeOrDefault 按类型获取Bean,如果不存在返回默认值

func (*ApplicationContextHelper) GetBoolProperty

func (h *ApplicationContextHelper) GetBoolProperty(key string, defaultVal bool) bool

GetBoolProperty 获取布尔类型属性

func (*ApplicationContextHelper) GetIntProperty

func (h *ApplicationContextHelper) GetIntProperty(key string, defaultVal int) int

GetIntProperty 获取整数类型属性

func (*ApplicationContextHelper) GetPhase

GetPhase 获取当前生命周期阶段

func (*ApplicationContextHelper) GetProperty

func (h *ApplicationContextHelper) GetProperty(key string, defaultVal string) string

GetProperty 获取字符串类型属性

func (*ApplicationContextHelper) HasBeanByType

func (h *ApplicationContextHelper) HasBeanByType(t reflect.Type) bool

HasBeanByType 检查指定类型的Bean是否存在

func (*ApplicationContextHelper) Invoke

func (h *ApplicationContextHelper) Invoke(fn any) error

Invoke 调用函数并自动注入依赖

func (*ApplicationContextHelper) IsDev

func (h *ApplicationContextHelper) IsDev() bool

IsDev 检查是否为开发环境

func (*ApplicationContextHelper) IsProd

func (h *ApplicationContextHelper) IsProd() bool

IsProd 检查是否为生产环境

func (*ApplicationContextHelper) IsRunning

func (h *ApplicationContextHelper) IsRunning() bool

IsRunning 检查应用是否运行中

func (*ApplicationContextHelper) PublishEvent

func (h *ApplicationContextHelper) PublishEvent(eventType string)

PublishEvent 发布事件

func (*ApplicationContextHelper) PublishReady

func (h *ApplicationContextHelper) PublishReady()

PublishReady 发布应用就绪事件

func (*ApplicationContextHelper) PublishStarted

func (h *ApplicationContextHelper) PublishStarted()

PublishStarted 发布应用启动事件

func (*ApplicationContextHelper) PublishStopped

func (h *ApplicationContextHelper) PublishStopped()

PublishStopped 发布应用停止事件

type ApplicationRunner

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

ApplicationRunner 应用运行器,简化应用的启动和停止

func NewApplicationRunner

func NewApplicationRunner(ctx ApplicationContext) *ApplicationRunner

NewApplicationRunner 创建应用运行器

func (*ApplicationRunner) Context

Context 获取应用上下文

func (*ApplicationRunner) Run

func (r *ApplicationRunner) Run() error

Run 运行应用,阻塞直到应用停止

func (*ApplicationRunner) Stop

func (r *ApplicationRunner) Stop() error

Stop 停止应用

type AsyncEventPublisher

type AsyncEventPublisher interface {
	// PublishAsync 异步发布事件,使用背景上下文。
	PublishAsync(event event.ApplicationEvent)

	// PublishAsyncWithCtx 异步发布事件,使用指定上下文(支持超时控制)。
	PublishAsyncWithCtx(ctx context.Context, event event.ApplicationEvent)
}

AsyncEventPublisher 异步事件发布器接口。

支持异步事件发布,不阻塞调用者。

type DefaultApplicationContext

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

DefaultApplicationContext 默认应用上下文实现。

组合了 IoC 容器、环境配置、生命周期管理和事件总线, 提供 enhance 框架的核心运行时能力。

func NewApplicationContext

func NewApplicationContext(container core.Container, env *environment.Environment, opts ...refresh.RefreshOption) *DefaultApplicationContext

NewApplicationContext 创建默认应用上下文实例。

func (*DefaultApplicationContext) AsyncEventPublisher

func (c *DefaultApplicationContext) AsyncEventPublisher() AsyncEventPublisher

func (*DefaultApplicationContext) Container

func (c *DefaultApplicationContext) Container() core.Container

func (*DefaultApplicationContext) Environment

func (*DefaultApplicationContext) EventBus

func (*DefaultApplicationContext) EventPublisher

func (c *DefaultApplicationContext) EventPublisher() EventPublisher

func (*DefaultApplicationContext) GetByType

func (c *DefaultApplicationContext) GetByType(t reflect.Type) (any, error)

func (*DefaultApplicationContext) GetProperty

func (c *DefaultApplicationContext) GetProperty(key string) (any, bool)

func (*DefaultApplicationContext) HasProperty

func (c *DefaultApplicationContext) HasProperty(key string) bool

func (*DefaultApplicationContext) Invoke

func (c *DefaultApplicationContext) Invoke(fn any) error

func (*DefaultApplicationContext) IsRunning

func (c *DefaultApplicationContext) IsRunning() bool

IsRunning 检查应用是否运行中

func (*DefaultApplicationContext) Lifecycle

func (*DefaultApplicationContext) RefreshScopeManager

func (c *DefaultApplicationContext) RefreshScopeManager() *refresh.RefreshScopeManager

func (*DefaultApplicationContext) Register

func (c *DefaultApplicationContext) Register(t reflect.Type, opts ...core.BeanOption) error

func (*DefaultApplicationContext) Start

func (c *DefaultApplicationContext) Start() error

Start 启动应用:PhaseInit → PhaseRunning

func (*DefaultApplicationContext) Stop

func (c *DefaultApplicationContext) Stop() error

Stop 停止应用:PhaseRunning → PhaseStopped

type EventBusAccess

type EventBusAccess interface {
	// Publish 发布事件。
	Publish(event event.ApplicationEvent)

	// Subscribe 订阅指定类型的事件。
	Subscribe(eventType string, listener event.EventListener)

	// Unsubscribe 取消订阅指定类型的事件。
	Unsubscribe(eventType string, target event.EventListener)
}

EventBusAccess 事件总线访问接口。

定义事件总线的公共操作,支持 EventBus 和 EventBusWithOrdering。

type EventPublisher

type EventPublisher interface {
	// Publish 发布事件。
	Publish(event event.ApplicationEvent)
}

EventPublisher 事件发布器接口。

用于解耦事件发布逻辑,便于测试和替换实现。

Jump to

Keyboard shortcuts

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