boot

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: 22 Imported by: 0

README

boot 包 — 应用启动器

所属层级: Boot Layer
设计理念: 自动配置,快速启动
设计灵感: Spring Boot SpringApplication

概述

boot 包是 enhance 框架的应用启动核心,提供应用启动的全生命周期管理。支持自动配置、启动器管理、横幅打印、失败分析等特性。

核心功能
功能 说明
自动配置 各模块通过 RegisterAutoConfig 注册自动配置
启动器管理 管理组件的启动和停止生命周期
横幅打印 应用启动时显示 ASCII 艺术横幅
失败分析 启动失败时提供友好的错误提示
配置加载 灵活的配置加载机制,支持多环境配置
覆盖机制 用户自定义配置覆盖默认自动配置

核心接口

Boot 结构体
type Boot struct {
    ctx           *contextpkg.DefaultApplicationContext
    config        *BootConfig
    configLoader  *environment.ConfigLoader
    starters      []Starter
}

主要方法:

方法 说明
Start() 启动应用,执行完整的生命周期
Stop() 停止应用,优雅关闭
IsRunning() 检查应用是否运行中
WaitForSignal() 等待终止信号(SIGINT/SIGTERM),自动优雅关闭
Context() 返回应用上下文
Container() 返回 IoC 容器
Environment() 返回环境配置
Starter 接口
type Starter interface {
    Name() string
    Dependencies() []string
    Configure(ctx ApplicationContext) error
    Start(ctx ApplicationContext) error
    Stop(ctx ApplicationContext) error
    GetCondition() condition.Condition
}
AutoConfiguration 接口
type AutoConfiguration interface {
    Configure(ctx ApplicationContext) error
}
Banner 接口
type Banner interface {
    Print(ctx ApplicationContext)
}
FailureAnalyzer 接口
type FailureAnalyzer interface {
    CanAnalyze(err error) bool
    Analyze(err error) *FailureReport
}

快速开始

创建应用
package main

import (
    "log"
    "github.com/xudefa/enhance/boot"
)

func main() {
    app, err := boot.NewApplication(
        boot.WithAppName("my-app"),
        boot.WithVersion("1.0.0"),
        boot.WithProfiles("dev"),
    )
    if err != nil {
        log.Fatal(err)
    }

    if err := app.Start(); err != nil {
        log.Fatal(err)
    }
    defer app.Stop()

    app.WaitForSignal()
}
函数式选项
选项 说明
WithAppName(name) 设置应用名称
WithVersion(version) 设置版本号
WithProfiles(profiles...) 设置激活的 Profile
WithConfigLocation(location) 设置配置文件路径
WithConfigType(configType) 设置配置文件类型 (json/yaml)
WithPropertySource(source) 添加自定义配置源
WithoutAutoConfig() 禁用自动配置执行
WithoutStarters() 禁用启动器自动管理

API 参考

配置加载
配置文件命名
  • 基础配置:application.json
  • 环境特定配置:application-{profile}.json
配置文件搜索路径(按优先级)
  1. /etc/config
  2. 当前目录
  3. ./config
  4. 可执行文件所在目录
  5. 可执行文件所在目录的 ./config
配置加载顺序
  1. 加载基础配置
  2. 加载环境特定配置
  3. 环境特定配置覆盖基础配置
自动配置
注册自动配置
func init() {
    boot.RegisterAutoConfig(&GinAutoConfiguration{},
        condition.OnProperty("gin.enabled", "true"),
    )
}
带选项的注册
func init() {
    boot.RegisterAutoConfigWith(&GinAutoConfiguration{},
        boot.WithOrder(int(boot.OrderPriorityWebLayer)),
        boot.WithDependsOn("dbConfig", "redisConfig"),
    )
}
覆盖机制
func init() {
    // 覆盖默认的 Gin 自动配置
    boot.RegisterAutoConfigWith(&MyGinConfig{},
        boot.WithOverride("*GinAutoConfiguration"),
        // Order 默认设置为 -100,确保在原始配置之前执行
    )
}
执行顺序优先级

框架定义了 9 个执行顺序层级,值越小优先级越高:

优先级常量 适用组件
OrderPriorityInfrastructure -3000 日志、配置中心等基础设施
OrderPriorityDataLayer -2000 数据库、缓存、对象存储
OrderPriorityAuthentication -1500 JWT、OAuth2、LDAP 认证
OrderPriorityAuthorizationGorm -1300 Casbin GORM 适配器等数据库授权适配器
OrderPriorityAuthorization -1200 Casbin、RBAC、ABAC 授权
OrderPrioritySecurityCore -100 安全过滤器链、访问控制
OrderPriorityWebLayer 0 HTTP 服务器、路由、中间件
OrderPriorityBusinessLayer 1000 定时任务、消息队列、事件总线
OrderPriorityMonitoringLayer 2000 Actuator、健康检查、链路追踪

依赖关系示例

日志(-3000) → 数据库(-2000) → 认证(-1500) → CasbinGorm(-1300) → Casbin(-1200) → 安全(-100) → Web(0) → 业务(1000) → 监控(2000)

第三方插件集成指南

  • Redis 缓存: OrderPriorityDataLayer (-2000)
  • 消息队列: OrderPriorityBusinessLayer (1000)
  • 对象存储: OrderPriorityDataLayer (-2000)
  • 搜索引擎: OrderPriorityDataLayer (-2000)
  • 链路追踪: OrderPriorityMonitoringLayer (2000)
  • 指标收集: OrderPriorityMonitoringLayer (2000)
启动器
注册启动器
func init() {
    boot.RegisterStarter(MyStarter{})
}
依赖拓扑排序

GetOrdered() 使用 Kahn 算法对启动器进行拓扑排序:

A → B → C
A → C

排序结果: [A, B, C]

逆序停止:停止时按排序结果的逆序执行,保证依赖方先于被依赖方停止。

横幅
内置实现
类型 说明
LegacyBanner 默认 ASCII 艺术横幅
TextBanner 文本横幅,支持属性模板
ASCIIArtBanner ASCII 艺术横幅
CustomTemplateBanner 自定义模板横幅
默认横幅效果
  ________                  ____             __
 /  _____/  ____    ____   / __ )  ____     / /_
/   \  ___ /  _ \  /  _ \ / __  | / __ \   / __ \
\    \_\  (  <_> )(  <_> ) /_/ / / /_/ /  / /_/ /
 \______  /\____/  \____/_____/  \____/   /___/
        \/
:: my-app :: v1.0.0 :: profiles(dev)
失败分析
FailureReport
type FailureReport struct {
    Headline          string
    Description       string
    Action            string
    Cause             string
    Details           map[string]any
    StackTrace        string
    PossibleSolutions []string
}
注册失败分析器
boot.RegisterFailureAnalyzer(MyAnalyzer{})

或使用 SimpleFailureAnalyzer

boot.RegisterFailureAnalyzer(
    boot.NewSimpleFailureAnalyzer(func(err error) *boot.FailureReport {
        if strings.Contains(err.Error(), "port") {
            return &boot.FailureReport{
                Description: "端口被占用",
                Action:      "请检查端口是否被其他进程占用",
                Cause:       err.Error(),
            }
        }
        return nil
    }),
)
失败报告输出
====================
APPLICATION FAILED TO START
====================

描述: 端口被占用

动作: 请检查端口是否被其他进程占用

原因: listen tcp :8080: bind: address already in use

可能的解决方案:
  1. 检查端口占用:lsof -i :8080
  2. 修改配置文件中的端口号
  3. 停止占用端口的进程
结构化启动错误(BootError)
type BootError struct {
    Phase       string   // 错误发生的阶段
    Original    error    // 原始错误
    Analyzed    string   // FailureAnalyzer 分析结果
    Suggestions []string // 修复建议
}
错误阶段
阶段 说明
configuring 配置加载和自动配置阶段
context-refreshed 上下文刷新阶段
starting 启动器启动阶段
stopping 停止阶段
使用示例
app, err := boot.NewApplication()
if err != nil {
    if bootErr, ok := err.(*boot.BootError); ok {
        fmt.Printf("启动失败阶段: %s\n", bootErr.Phase)
        fmt.Printf("原始错误: %v\n", bootErr.Original)
        if bootErr.Analyzed != "" {
            fmt.Printf("分析: %s\n", bootErr.Analyzed)
        }
        for _, s := range bootErr.Suggestions {
            fmt.Printf("建议: %s\n", s)
        }
    }
}

启动流程

启动阶段
PhaseInitializing
    ↓
PhaseConfiguring
    ├── 执行 AutoConfiguration(按顺序)
    ├── 注册 Starter(拓扑排序)
    ├── 调用 Starter.Configure()
    └── 发布 EventEnvironmentPrepared
    ↓
PhaseContextRefreshed
    ├── 发布 EventContextRefreshed
    ↓
PhaseReady
    ├── 调用 Starter.Start()
    ├── 打印 Banner
    ↓
PhaseRunning
    ├── 发布 EventApplicationStarted
    └── 发布 EventApplicationReady
停止流程
PhaseRunning
    ↓
PhaseStopping
    ├── 逆序停止 Starter(反向依赖顺序)
    ↓
PhaseStopped
    └── 发布 EventApplicationStopped

使用示例

自定义启动器
type MyStarter struct{}

func (s *MyStarter) Name() string { return "my-starter" }
func (s *MyStarter) Dependencies() []string { return nil }
func (s *MyStarter) Configure(ctx boot.ApplicationContext) error {
    // 配置阶段逻辑
    return nil
}
func (s *MyStarter) Start(ctx boot.ApplicationContext) error {
    // 启动阶段逻辑
    return nil
}
func (s *MyStarter) Stop(ctx boot.ApplicationContext) error {
    // 停止阶段逻辑
    return nil
}
func (s *MyStarter) GetCondition() condition.Condition {
    return condition.OnProperty("my.enabled", "true")
}

func init() {
    boot.RegisterStarter(&MyStarter{})
}
自定义横幅
type MyBanner struct{}

func (b *MyBanner) Print(ctx boot.ApplicationContext) {
    fmt.Println("================================")
    fmt.Println("  My Application Starting...")
    fmt.Println("================================")
}

// 使用自定义横幅
app, _ := boot.NewApplication()
app.SetBanner(&MyBanner{})

最佳实践

1. 使用自动配置简化集成
// ✅ 推荐:使用自动配置
func init() {
    boot.RegisterAutoConfig(&RedisAutoConfiguration{},
        condition.OnProperty("redis.enabled", "true"),
    )
}

// ⚠️ 不推荐:手动配置所有组件
func main() {
    // 手动创建和配置所有组件
}
2. 合理使用启动器依赖
// ✅ 推荐:声明依赖关系
func (s *MyStarter) Dependencies() []string {
    return []string{"dbStarter", "redisStarter"}
}

// ⚠️ 不推荐:不声明依赖,可能导致初始化顺序错误
func (s *MyStarter) Dependencies() []string {
    return nil
}
3. 使用条件控制启动器启用
// ✅ 推荐:使用条件控制
func (s *MyStarter) GetCondition() condition.Condition {
    return condition.All(
        condition.OnProperty("my.enabled", "true"),
        condition.OnClass("github.com/some/lib"),
    )
}
4. 优雅关闭应用
// ✅ 推荐:使用 WaitForSignal 等待终止信号
func main() {
    app, _ := boot.NewApplication()
    app.Start()
    defer app.Stop()
    
    app.WaitForSignal() // 等待 SIGINT/SIGTERM
}
5. 自定义失败分析器
// ✅ 推荐:提供友好的错误提示
boot.RegisterFailureAnalyzer(
    boot.NewSimpleFailureAnalyzer(func(err error) *boot.FailureReport {
        if strings.Contains(err.Error(), "connection refused") {
            return &boot.FailureReport{
                Description: "数据库连接失败",
                Action:      "请检查数据库服务是否启动,配置是否正确",
                Cause:       err.Error(),
                PossibleSolutions: []string{
                    "检查数据库服务状态",
                    "验证数据库连接配置",
                    "检查网络连接",
                },
            }
        }
        return nil
    }),
)

Documentation

Overview

Package boot 提供应用启动器功能,用于 enhance 框架。

Package boot 提供应用启动器功能,用于 enhance 框架。

Package boot 提供应用启动器功能,用于 enhance 框架。

Package boot 提供应用启动器功能,用于 enhance 框架。

Package boot 提供应用启动器功能,用于 enhance 框架。

该模块负责应用的生命周期管理、自动配置执行、组件扫描和注册等核心功能。 参考 Spring Boot 的 SpringApplication 设计。

架构设计

  • Application: 应用接口,管理完整的应用生命周期
  • AutoConfiguration: 自动配置接口,支持条件化配置
  • Starter: 启动器接口,支持模块化启动
  • StarterRegistry: 启动器注册表接口,管理 Starter 的注册和依赖排序
  • BootError: 结构化启动错误接口,提供错误码和错误信息
  • FailureAnalyzer: 失败分析器接口,提供友好的错误提示
  • Banner: 启动横幅接口,支持多种格式的启动横幅显示
  • Module: 可组合的配置单元,包含 Bean 注册和 Starter
  • BeanProvider: Bean 提供者函数类型
  • ApplicationContext: 自动配置看到的上下文接口
  • OrderPriority: 执行顺序优先级枚举,用于规范自动配置的执行顺序

核心功能

  • 自动配置执行(AutoConfiguration)
  • 组件扫描和注册
  • 生命周期管理
  • 启动横幅(Banner)显示
  • 启动失败分析
  • 优雅关闭支持

执行顺序设计

自动配置的执行顺序通过 OrderPriority 枚举定义,值越小优先级越高:

  • OrderPriorityInfrastructure (-3000): 基础设施层(日志、配置中心等)
  • OrderPriorityDataLayer (-2000): 数据层(数据库、缓存等)
  • OrderPriorityAuthentication (-1500): 认证层(JWT、OAuth2 等)
  • OrderPriorityAuthorizationGorm (-1300): 授权层-GORM 适配器(CasbinGorm 等)
  • OrderPriorityAuthorization (-1200): 授权层(Casbin、RBAC 等)
  • OrderPrioritySecurityCore (-100): 安全核心层(过滤器链、访问控制等)
  • OrderPriorityWebLayer (0): Web 层(HTTP 服务器、路由等)
  • OrderPriorityBusinessLayer (1000): 业务层(定时任务、消息队列等)
  • OrderPriorityMonitoringLayer (2000): 监控层(Actuator、健康检查等)

依赖关系示例:

日志(-3000) → 数据库(-2000) → 认证(-1500) → CasbinGorm(-1300) → Casbin(-1200) → 安全(-100) → Web(0) → 业务(1000) → 监控(2000)

使用方式

创建应用实例:

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithVersion("1.0.0"),
    boot.WithProfiles("dev"),
)
if err != nil {
    log.Fatal(err)
}
app.Start()

自动配置

自动配置类通过实现 boot.AutoConfiguration 接口,在应用启动时自动执行:

type MyAutoConfiguration struct{}

func (m *MyAutoConfiguration) Configure(ctx boot.ApplicationContext) error {
    // 配置逻辑
    return nil
}

func init() {
    boot.RegisterAutoConfig(&MyAutoConfiguration{})
}

配置选项

  • WithAppName: 设置应用名称
  • WithVersion: 设置版本号
  • WithProfiles: 设置激活的 Profile
  • WithConfigLocation: 设置配置文件路径
  • WithProperty: 添加单个配置属性

Package boot 提供应用启动器功能,用于 enhance 框架。

Package boot 提供应用启动器功能,用于 enhance 框架。

Index

Examples

Constants

View Source
const (
	ErrCodeConfigLoad    = "BOOT_CONFIG_LOAD"    // 配置加载失败
	ErrCodeConfigCenter  = "BOOT_CONFIG_CENTER"  // 配置中心加载失败
	ErrCodeAutoConfig    = "BOOT_AUTO_CONFIG"    // 自动配置执行失败
	ErrCodeModuleInstall = "BOOT_MODULE_INSTALL" // 模块安装失败
	ErrCodeStarterConfig = "BOOT_STARTER_CONFIG" // Starter 配置失败
	ErrCodeStarterStart  = "BOOT_STARTER_START"  // Starter 启动失败
	ErrCodeLifecycle     = "BOOT_LIFECYCLE"      // 生命周期阶段错误
	ErrCodeUnknown       = "BOOT_UNKNOWN"        // 未知错误
)

错误码常量,用于程序化错误处理。

View Source
const (
	BannerModeConsole = banner.BannerModeConsole
	BannerModeLog     = banner.BannerModeLog
	BannerModeOff     = banner.BannerModeOff
)

Variables

View Source
var (
	NewLegacyBanner    = banner.NewLegacyBanner
	BannerWithLines    = banner.WithLines
	BannerWithAppName  = banner.WithAppName
	BannerWithProfiles = banner.WithProfiles
)
View Source
var (
	// ErrPropertyNotFound 配置项未找到。
	ErrPropertyNotFound = errors.New("property not found")

	// ErrTypeConversion 类型转换失败。
	ErrTypeConversion = errors.New("type conversion failed")
)

配置错误。

View Source
var DefaultBanner banner.Banner = banner.NewLegacyBanner(
	banner.WithLines([]string{
		`
#####  #   #  #   #   ###   #   #  #####  #####
#      ##  #  #   #  #   #  ##  #  #      #    
#####  # # #  #####  #####  # # #  #      #####
#      #  ##  #   #  #   #  #  ##  #      #    
#####  #   #  #   #  #   #  #   #  #####  #####
		`,
	}),
)

DefaultBanner 默认横幅实例

Functions

func BindConfig

func BindConfig[T any](b *Boot, opts ...BindConfigOption) (T, error)

BindConfig 将配置绑定到指定类型的结构体(泛型版本)

示例:

cfg, err := bootApp.BindConfig[ServerConfig]()
// 或带前缀:
cfg, err := bootApp.BindConfig[ServerConfig](boot.WithConfigPrefix("server"))

func DisableAutoConfigReport

func DisableAutoConfigReport()

DisableAutoConfigReport 禁用自动配置报告

func EnableAutoConfigReport

func EnableAutoConfigReport()

EnableAutoConfigReport 启用自动配置报告

func IsAutoConfigReportEnabled

func IsAutoConfigReportEnabled() bool

IsAutoConfigReportEnabled 检查自动配置报告是否启用

func NewBanner

func NewBanner(opts ...banner.LegacyOption) banner.Banner

NewBanner 创建旧版横幅

参数 opts: 可选配置项,如 banner.WithLines, banner.WithAppName, banner.WithProfiles

func RegisterAutoConfig

func RegisterAutoConfig(config AutoConfiguration, conditions ...condition.Condition)

RegisterAutoConfig 注册自动配置到全局注册表

在模块的 init() 中调用:

func init() {
    boot.RegisterAutoConfig(&CircuitAutoConfiguration{},
        condition.OnProperty("circuit.enabled", "true"),
    )
}

func RegisterAutoConfigWith

func RegisterAutoConfigWith(config AutoConfiguration, opts ...AutoConfigurationOption)

RegisterAutoConfigWith 注册自动配置到全局注册表(支持选项)

func RegisterConfigCenterFactory

func RegisterConfigCenterFactory(centerType string, factory ConfigCenterFactory)

RegisterConfigCenterFactory 注册配置中心工厂函数

func RegisterFailureAnalyzer

func RegisterFailureAnalyzer(analyzer FailureAnalyzer)

RegisterFailureAnalyzer 注册失败分析器到全局注册表

func RegisterStarter

func RegisterStarter(starter Starter)

RegisterStarter 注册启动器到全局注册表。

在模块的 init() 中调用:

func init() {
    boot.RegisterStarter(&MyStarter{})
}

func ReportFailure

func ReportFailure(err error) string

ReportFailure 分析并格式化输出失败报告

如果没有匹配的分析器,返回简单的错误信息字符串。

func ResetAutoConfigReport

func ResetAutoConfigReport()

ResetAutoConfigReport 重置全局报告

func Run

func Run(opts ...any)

Run 启动应用并等待信号(一行启动)

参考 Spring Boot 的 SpringApplication.run() 方法, 一行代码直接启动应用,自动加载 JSON 配置文件,阻塞直到应用关闭。

默认行为:

  • 自动加载 application.json 配置文件
  • 自动执行 AutoConfiguration
  • 自动启动所有 Starter
  • 阻塞等待 SIGINT/SIGTERM 信号
  • 收到信号后自动优雅关闭

示例(最简用法):

func main() {
    boot.Run()
}

示例(带选项):

func main() {
    boot.Run(
        boot.WithAppName("my-app"),
        boot.WithVersion("1.0.0"),
        boot.WithProfiles("dev"),
    )
}

示例(带模块):

func main() {
    boot.Run(
        boot.WithAppName("my-app"),
        boot.WithModulesOption(WebModule, DatabaseModule),
    )
}

func ValidateStarters

func ValidateStarters(starters []StarterModule) error

ValidateStarters 验证 Starter 列表的有效性

返回错误信息(如果有冲突)或 nil(如果有效)。

Types

type ASCIIArtBanner

type ASCIIArtBanner = banner.ASCIIArtBanner

type Application added in v0.0.3

type Application interface {
	// Start 启动应用,执行完整的初始化流程。
	// 包括配置加载、自动配置执行、Starter 配置和启动。
	Start() error

	// Stop 停止应用,逆序释放所有资源。
	Stop() error

	// WaitForSignal 阻塞等待 SIGINT/SIGTERM 信号,收到后自动执行优雅关闭。
	WaitForSignal()

	// Context 返回应用上下文,包含 IoC 容器和环境配置。
	Context() ApplicationContext

	// Config 返回启动配置。
	Config() *BootConfig
}

Application 应用接口,管理应用的完整生命周期。

Boot 结构体实现了此接口的所有方法(Context() 返回具体类型)。 NewApplication 返回 *Boot,可直接调用 Start/Stop/WaitForSignal。 需要接口类型的场景(如测试 mock)可使用此接口。

示例:

app, _ := boot.NewApplication(boot.WithAppName("my-app"))
app.Start()  // 直接使用 *Boot

// 需要接口类型时:
var iface boot.Application = app
iface.Start()

type ApplicationContext

type ApplicationContext interface {
	// Context 返回应用级别的 Go 标准 context.Context。
	//
	// 该 context 在应用启动时创建,在应用停止时取消。
	// Starters 和 AutoConfigurations 应使用此 context 进行日志记录、
	// 超时控制和取消传播,避免使用 context.Background()。
	Context() context.Context

	// Container 返回 IoC 容器实例。
	Container() core.Container

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

	// Register 在容器中注册 Bean。
	Register(t reflect.Type, opts ...core.BeanOption) error

	// GetByType 从容器中获取指定类型的 Bean。
	GetByType(t reflect.Type) (any, error)

	// EventBus 返回事件总线访问接口。
	EventBus() EventBusResult
}

ApplicationContext 自动配置看到的上下文接口。

实际由 context.DefaultApplicationContext 实现。 这是 context.ApplicationContext 的子集,仅包含自动配置需要的方法。

type ApplicationOption

type ApplicationOption func(*Boot) error

ApplicationOption 应用级选项函数

用于 NewApplication 中,在应用创建后执行自定义逻辑。

func WithModulesOption

func WithModulesOption(modules ...any) ApplicationOption

WithModulesOption 通过 ApplicationOption 方式添加模块

支持 Module 和 *ModuleBuilder 混合使用。

示例:

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithModulesOption(DatabaseModule, WebModule),
)

type AutoConfigEntry

type AutoConfigEntry struct {
	Config         AutoConfiguration     // 自动配置实例
	Conditions     []condition.Condition // 条件列表
	Order          int                   // 执行顺序,值越小优先级越高
	Dependencies   []string              // 依赖的配置名称
	Override       bool                  // 是否为覆盖配置(用户自定义优先)
	OverrideTarget string                // 被覆盖的自动配置类型名
	Before         []string              // 此配置应在哪些配置之前执行
	After          []string              // 此配置应在哪些配置之后执行
}

AutoConfigEntry 自动配置条目。

type AutoConfigMatchResult

type AutoConfigMatchResult struct {
	// Name 自动配置名称
	Name string
	// Matched 是否匹配成功
	Matched bool
	// Conditions 条件列表及匹配结果
	Conditions []ConditionResult
}

AutoConfigMatchResult 自动配置匹配结果

type AutoConfigRegistry

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

AutoConfigRegistry 自动配置注册表

func GlobalRegistry

func GlobalRegistry() *AutoConfigRegistry

GlobalRegistry 返回全局注册表

func NewAutoConfigRegistry

func NewAutoConfigRegistry() *AutoConfigRegistry

NewAutoConfigRegistry 创建注册表

func (*AutoConfigRegistry) Add

func (r *AutoConfigRegistry) Add(entry AutoConfigEntry)

Add 添加自动配置条目

func (*AutoConfigRegistry) GetAll

func (r *AutoConfigRegistry) GetAll() []AutoConfigEntry

GetAll 获取所有注册的自动配置

func (*AutoConfigRegistry) GetMatching

GetMatching 获取匹配条件的自动配置(按 Order 排序,支持覆盖机制和 Before/After 排序)

处理逻辑:

  1. 收集所有 Override 配置的目标类型
  2. 过滤被覆盖的配置(跳过被覆盖的自动配置)
  3. 按 Order、Before、After 排序返回

func (*AutoConfigRegistry) GetMatchingWithExclude

func (r *AutoConfigRegistry) GetMatchingWithExclude(ctx condition.ConditionContext, excluded []string) []AutoConfigEntry

GetMatchingWithExclude 获取匹配条件的自动配置,支持排除列表

参数:

  • ctx: 条件判断上下文
  • excluded: 需要排除的自动配置类型名列表

处理逻辑:

  1. 收集所有 Override 配置的目标类型
  2. 过滤被覆盖的配置(跳过被覆盖的自动配置)
  3. 过滤被排除的配置
  4. 按 Order、Before、After 排序返回

type AutoConfiguration

type AutoConfiguration interface {
	// Configure 执行自动配置逻辑。
	Configure(ctx ApplicationContext) error
}

AutoConfiguration 自动配置接口。

参考 Spring Boot 的 @Configuration + @Bean 模式。 每个模块实现此接口,通过 RegisterAutoConfig 注册。

type AutoConfigurationOption

type AutoConfigurationOption func(entry *AutoConfigEntry)

AutoConfigurationOption 自动配置选项函数。

func WithAfter

func WithAfter(configs ...string) AutoConfigurationOption

WithAfter 设置此配置应在哪些配置之后执行

参数:

  • configs: 配置类型名列表

示例:

boot.RegisterAutoConfigWith(&WebConfig{},
    boot.WithAfter("databaseConfig"),
)

func WithBefore

func WithBefore(configs ...string) AutoConfigurationOption

WithBefore 设置此配置应在哪些配置之前执行

参数:

  • configs: 配置类型名列表

示例:

boot.RegisterAutoConfigWith(&DatabaseConfig{},
    boot.WithBefore("webConfig", "cacheConfig"),
)

func WithConditions

func WithConditions(conds ...condition.Condition) AutoConfigurationOption

WithConditions 设置条件

func WithDependsOn

func WithDependsOn(deps ...string) AutoConfigurationOption

WithDependsOn 设置依赖的配置名称

func WithOrder

func WithOrder(order int) AutoConfigurationOption

WithOrder 设置执行顺序,值越小优先级越高

推荐使用 OrderPriority 枚举常量,而非直接使用魔法数字:

boot.RegisterAutoConfigWith(&MyConfig{},
    boot.WithOrder(int(boot.OrderPriorityDataLayer)),
)

func WithOverride

func WithOverride(target string) AutoConfigurationOption

WithOverride 设置覆盖目标,用户自定义配置优先于自动配置

参数:

  • target: 被覆盖的自动配置类型名(如 "*GinAutoConfiguration")

示例:

boot.RegisterAutoConfigWith(&MyGinConfig{},
    boot.WithOverride("*GinAutoConfiguration"),
    boot.WithOrder(-100), // 确保在原始配置之前执行
)
type Banner = banner.Banner

Banner 是 banner.Banner 的类型别名,用于向后兼容。

新代码应直接使用 banner.Banner。

type BannerMode added in v0.0.3

type BannerMode = banner.BannerMode

向后兼容的类型别名,重新导出 banner 子包中的类型。

type BeanNotFoundAnalyzer

type BeanNotFoundAnalyzer struct{}

BeanNotFoundAnalyzer Bean 未找到错误分析器

func NewBeanNotFoundAnalyzer

func NewBeanNotFoundAnalyzer() *BeanNotFoundAnalyzer

NewBeanNotFoundAnalyzer 创建 Bean 未找到错误分析器

func (*BeanNotFoundAnalyzer) Analyze

func (a *BeanNotFoundAnalyzer) Analyze(err error) *FailureReport

Analyze 分析错误并返回失败报告

func (*BeanNotFoundAnalyzer) CanAnalyze

func (a *BeanNotFoundAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查是否能分析该错误

type BeanProvider

type BeanProvider func(c core.Container) error

BeanProvider Bean 提供者函数类型。

定义如何向容器注册 Bean,是 Module 中 Bean 注册的统一抽象。

func Invoke

func Invoke(fn any) BeanProvider

Invoke 创建一个安装时立即调用的函数

用于在模块安装后执行初始化逻辑(如数据库迁移、缓存预热等)。 函数的参数会自动从容器中注入。

示例:

boot.Invoke(func(db *Database) error {
    return db.Migrate()
})

func Provide

func Provide(constructor any) BeanProvider

Provide 通过构造函数注册 Bean

构造函数返回值类型将作为 Bean 的类型。 构造函数的参数将自动从容器中注入。

示例:

func NewUserService(repo UserRepository) *UserService {
    return &UserService{repo: repo}
}

boot.Provide(NewUserService)

func ProvideBean

func ProvideBean[T any](bean T, opts ...core.BeanOption) BeanProvider

ProvideBean 注册现有实例

示例:

cfg := &Config{Port: 8080}
boot.ProvideBean(cfg)

func ProvideFactory

func ProvideFactory[T any](factory func(core.Container) (T, error), opts ...core.BeanOption) BeanProvider

ProvideFactory 注册工厂函数

示例:

boot.ProvideFactory(func(c core.Container) (*Database, error) {
    return NewDatabase("localhost:5432")
})

func ProvideNamed

func ProvideNamed[T any](name string, bean T, opts ...core.BeanOption) BeanProvider

ProvideNamed 注册带名称的 Bean

示例:

boot.ProvideNamed("primary", primaryDB)
boot.ProvideNamed("readonly", readonlyDB)

func ProvidePrimary

func ProvidePrimary[T any](bean T, opts ...core.BeanOption) BeanProvider

ProvidePrimary 注册主要 Bean(优先注入)

示例:

boot.ProvidePrimary(primaryDB) // 当有多个 Database 时优先注入

type BindConfigOption

type BindConfigOption func(*bindConfigOpts)

BindConfigOption 配置绑定选项

func WithConfigPrefix

func WithConfigPrefix(prefix string) BindConfigOption

WithConfigPrefix 设置配置绑定前缀

type Boot

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

Boot 应用启动器,管理应用的完整生命周期

参考 Spring Boot 的 SpringApplication,负责:

  • 自动配置执行(AutoConfiguration)
  • 启动器管理(Starter 的 Configure/Start/Stop)
  • 生命周期阶段流转
  • 事件发布
  • 优雅关闭

func NewApplication

func NewApplication(opts ...any) (*Boot, error)

NewApplication 创建新的应用实例。

这是 enhance 框架的推荐入口点,支持 BootOption 和 ApplicationOption 混合使用。 自动配置(AutoConfiguration)和启动器(Starter)会在 Start() 方法中按生命周期阶段自动执行。

参数:

  • opts: 可选的配置选项,支持 BootOption 和 ApplicationOption 混合传入

返回值:

  • *Boot: 应用启动器实例,可用于后续的 Start/Stop 操作
  • error: 创建失败时返回错误(通常是 ApplicationOption 执行失败)

示例(基础用法):

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithVersion("1.0.0"),
    boot.WithProfiles("dev"),
)
if err != nil {
    log.Fatal(err)
}
app.Start()

示例(带模块):

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithModulesOption(DatabaseModule, WebModule),
)

启动流程说明:

  1. 创建 IoC 容器和环境配置
  2. 加载配置文件并注册到环境
  3. 执行自动配置(AutoConfiguration)
  4. 安装显式模块(Modules)
  5. 配置并启动所有 Starter
  6. 发布生命周期事件

注意:

  • 该方法只创建应用实例,不会启动应用
  • 需要显式调用 Start() 方法才会执行完整的启动流程
  • 支持多次调用 NewApplication 创建多个独立的应用实例

func NewApplicationFromRunOptions

func NewApplicationFromRunOptions(opts ...any) (*Boot, error)

NewApplicationFromRunOptions 从 Run 选项创建应用

支持 BootOption 和 ApplicationOption 混合使用。

func (*Boot) Config added in v0.0.3

func (b *Boot) Config() *BootConfig

Config 返回启动配置。

func (*Boot) Container

func (b *Boot) Container() core.Container

Container 返回 IoC 容器

func (*Boot) Context

func (b *Boot) Context() ApplicationContext

Context 返回应用上下文(返回接口类型,便于多态使用)。

返回 ApplicationContext 接口,包含 IoC 容器、环境配置等核心组件。 如需访问 DefaultApplicationContext 的完整 API,可通过类型断言获取:

dc, ok := boot.Context().(*contextpkg.DefaultApplicationContext)

func (*Boot) Environment

func (b *Boot) Environment() *environment.Environment

Environment 返回环境配置

func (*Boot) IsRunning

func (b *Boot) IsRunning() bool

IsRunning 检查应用是否运行中

func (*Boot) Start

func (b *Boot) Start() (err error)

Start 启动应用,执行完整的生命周期

启动流程简化为 3 阶段:

  1. PhaseInit:加载配置、注册 Bean、启动启动器
  2. PhaseRunning:应用正常运行

func (*Boot) Stop

func (b *Boot) Stop() error

Stop 停止应用

流程:

  1. 逆序停止启动器
  2. 执行 OnStop 钩子
  3. 发布停止事件
  4. 取消应用根 context

注意:允许从任何阶段调用 Stop,以支持 Start() 部分失败时的资源清理。

func (*Boot) WaitForSignal

func (b *Boot) WaitForSignal()

WaitForSignal 等待终止信号,收到信号后自动执行优雅关闭

type BootConfig

type BootConfig struct {
	// 核心配置
	AppName     string   // 应用名称
	Version     string   // 版本号
	Profiles    []string // 激活的 Profile
	ConfigPaths []string // 配置文件搜索路径列表
	Port        int      // 服务端口(默认 8080)
	Debug       bool     // 调试模式(默认 false)

	// 配置文件
	ConfigLocation string // 配置文件路径(向后兼容,优先使用 ConfigPaths)
	ConfigType     string // 配置文件类型 (json)

	// 自动配置
	AutoExecute bool // 是否自动执行自动配置(默认 true)
	Starters    bool // 是否自动管理启动器生命周期(默认 true)

	// 排除的自动配置列表(按类型名匹配)
	ExcludedAutoConfigs []string // 需要排除的自动配置类型名

	// 自定义配置源
	CustomPropertySources []environment.PropertySource // 用户自定义配置源

	// 配置中心配置
	ConfigCenterEnabled bool          // 是否启用配置中心(默认 false)
	ConfigCenterType    string        // 配置中心类型 (nacos/etcd/consul)
	ConfigCenterAddr    []string      // 配置中心地址
	ConfigCenterDataID  string        // 配置中心数据ID
	ConfigCenterGroup   string        // 配置中心分组
	ConfigCenterPrefix  string        // 配置中心前缀
	ConfigCenterTimeout time.Duration // 配置中心超时时间

	// 显式模块(Go 风格组合,替代全局 init() 注册)
	Modules []Module // 用户显式传入的模块列表

	// 生命周期钩子(Go 风格 3 阶段:OnInit/OnStart/OnStop)
	Hooks []lifecycle.Hook // 用户注册的生命周期钩子
}

BootConfig 启动配置。

包含应用的核心配置信息。通过 BootOption 函数式选项模式进行配置。

type BootError

type BootError interface {
	// Code 返回错误码,用于程序化错误处理。
	Code() string

	// Message 返回人类可读的错误消息。
	Message() string

	// Cause 返回原始错误,用于错误链追踪。
	Cause() error

	// Error 实现 error 接口。
	Error() string

	// Unwrap 实现 errors.Unwrap 接口,支持 errors.Is/As。
	Unwrap() error
}

BootError 结构化启动错误接口。

提供标准化的错误信息访问方式,包含错误码、错误消息和原始错误。 通过 NewBootErr 创建实例,通过 errors.As 提取。

示例:

var bootErr boot.BootError
if errors.As(err, &bootErr) {
    fmt.Println(bootErr.Code(), bootErr.Message())
}

func NewBootErr added in v0.0.3

func NewBootErr(code, phase string, err error) BootError

NewBootErr 创建结构化启动错误(推荐使用)。

参数:

  • code: 错误码,用于程序化错误处理(如 ErrCodeConfigLoad)
  • phase: 错误发生的阶段(如 "初始化"、"启动"、"停止")
  • err: 原始错误

返回值:

  • BootError: 结构化错误接口,支持 Error/Unwrap/Code/Message/Cause

示例:

return boot.NewBootErr(boot.ErrCodeConfigLoad, "初始化", err)

func NewBootErrf added in v0.0.3

func NewBootErrf(code, phase, format string, args ...any) BootError

NewBootErrf 创建带格式化消息的结构化启动错误。

参数:

  • code: 错误码,用于程序化错误处理(如 ErrCodeAutoConfig)
  • phase: 错误发生的阶段(如 "初始化"、"启动"、"停止")
  • format: 格式化消息模板
  • args: 格式化参数

示例:

return boot.NewBootErrf(boot.ErrCodeAutoConfig, "初始化", "自动配置 %T 失败: %v", config, rootErr)

type BootErrorStruct added in v0.0.3

type BootErrorStruct = bootError

BootErrorStruct 是 bootError 实现类型的别名。

在重构前 BootError 是一个导出字段的结构体,现在改为接口。 此别名保留对底层实现类型的访问,便于需要类型断言的场景。

type BootOption

type BootOption func(*BootConfig)

BootOption 启动选项函数。

func WithAppName

func WithAppName(name string) BootOption

WithAppName 设置应用名称

func WithConfigCenter

func WithConfigCenter(centerType string, addr []string, opts ...ConfigCenterOption) BootOption

WithConfigCenter 启用配置中心

func WithConfigLocation

func WithConfigLocation(location string) BootOption

WithConfigLocation 设置配置文件路径

func WithConfigType

func WithConfigType(configType string) BootOption

WithConfigType 设置配置文件类型(如 json),为空时使用默认值。

func WithExclude

func WithExclude(configs ...string) BootOption

WithExclude 排除指定的自动配置

参数:

  • configs: 需要排除的自动配置类型名列表(如 "*DatabaseAutoConfiguration")

示例:

boot.Run(
    boot.WithExclude("DatabaseStarter"),
    boot.WithAutoConfigRegistry(registry),
)

func WithHook

func WithHook(hook lifecycle.Hook) BootOption

WithHook 添加生命周期钩子

func WithHookFunc

func WithHookFunc(onInit, onStart, onStop func(context.Context) error) BootOption

WithHookFunc 通过函数添加生命周期钩子

func WithModule

func WithModule(mod Module) BootOption

WithModule 添加单个模块

func WithModules

func WithModules(modules ...any) BootOption

WithModules 通过 BootOption 方式添加模块

支持 Module 和 *ModuleBuilder 混合使用。

示例:

app := boot.New(
    boot.WithAppName("my-app"),
    boot.WithModules(DatabaseModule, WebModule),
)

func WithProfiles

func WithProfiles(profiles ...string) BootOption

WithProfiles 设置激活的 Profile

func WithProperties

func WithProperties(props ...any) BootOption

WithProperties 批量添加配置属性。

参数:

  • props: 配置键值对(必须为偶数个参数,key-value 交替)

示例:

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithProperties(
        "tracing.enabled", "true",
        "server.port", 8080,
    ),
)

func WithProperty

func WithProperty(key string, value any) BootOption

WithProperty 添加单个配置属性,使用内置的 MapPropertySource。

参数:

  • key: 配置键(如 "tracing.enabled")
  • value: 配置值(任意类型)

示例:

app, err := boot.NewApplication(
    boot.WithAppName("my-app"),
    boot.WithProperty("tracing.enabled", "true"),
    boot.WithProperty("server.port", "8080"),
)

func WithPropertySource

func WithPropertySource(source environment.PropertySource) BootOption

WithPropertySource 添加自定义配置源,优先级最高。

func WithVersion

func WithVersion(version string) BootOption

WithVersion 设置版本号

func WithoutAutoConfig

func WithoutAutoConfig() BootOption

WithoutAutoConfig 禁用自动配置执行

func WithoutStarters

func WithoutStarters() BootOption

WithoutStarters 禁用启动器自动管理

type CircularDependencyAnalyzer

type CircularDependencyAnalyzer struct{}

CircularDependencyAnalyzer 循环依赖错误分析器

func NewCircularDependencyAnalyzer

func NewCircularDependencyAnalyzer() *CircularDependencyAnalyzer

NewCircularDependencyAnalyzer 创建循环依赖错误分析器

func (*CircularDependencyAnalyzer) Analyze

Analyze 分析错误并返回失败报告

func (*CircularDependencyAnalyzer) CanAnalyze

func (a *CircularDependencyAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查是否能分析该错误

type ConditionEvaluationReport

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

ConditionEvaluationReport 条件评估报告

记录所有自动配置的匹配情况,包括正面匹配、负面匹配、排除项和无条件类。

func GetAutoConfigReport

func GetAutoConfigReport() *ConditionEvaluationReport

GetAutoConfigReport 获取全局报告实例

func NewConditionEvaluationReport

func NewConditionEvaluationReport() *ConditionEvaluationReport

NewConditionEvaluationReport 创建条件评估报告

func (*ConditionEvaluationReport) Print

func (r *ConditionEvaluationReport) Print()

Print 打印报告到标准输出

func (*ConditionEvaluationReport) RecordExclusion

func (r *ConditionEvaluationReport) RecordExclusion(name string)

RecordExclusion 记录排除项

func (*ConditionEvaluationReport) RecordNegativeMatch

func (r *ConditionEvaluationReport) RecordNegativeMatch(name string, conditions []ConditionResult)

RecordNegativeMatch 记录负面匹配

func (*ConditionEvaluationReport) RecordPositiveMatch

func (r *ConditionEvaluationReport) RecordPositiveMatch(name string, conditions []ConditionResult)

RecordPositiveMatch 记录正面匹配

func (*ConditionEvaluationReport) RecordUnconditional

func (r *ConditionEvaluationReport) RecordUnconditional(name string)

RecordUnconditional 记录无条件类

func (*ConditionEvaluationReport) String

func (r *ConditionEvaluationReport) String() string

String 返回报告的字符串表示

type ConditionResult

type ConditionResult struct {
	// Condition 条件描述(如 "@ConditionalOnProperty")
	Condition string
	// Matched 是否匹配
	Matched bool
	// Message 详细信息
	Message string
}

ConditionResult 单个条件的匹配结果

type ConfigCenterFactory

type ConfigCenterFactory func(ctx context.Context, cfg *config.ConfigCenterConfig) (config.ConfigCenter, error)

ConfigCenterFactory 配置中心工厂函数类型

type ConfigCenterOption

type ConfigCenterOption func(*BootConfig)

ConfigCenterOption 配置中心选项函数

func WithConfigCenterDataID

func WithConfigCenterDataID(dataID string) ConfigCenterOption

WithConfigCenterDataID 设置配置中心数据ID

func WithConfigCenterGroup

func WithConfigCenterGroup(group string) ConfigCenterOption

WithConfigCenterGroup 设置配置中心分组

func WithConfigCenterPrefix

func WithConfigCenterPrefix(prefix string) ConfigCenterOption

WithConfigCenterPrefix 设置配置中心前缀

func WithConfigCenterTimeout

func WithConfigCenterTimeout(timeout time.Duration) ConfigCenterOption

WithConfigCenterTimeout 设置配置中心超时时间

type ConfigLoadAnalyzer

type ConfigLoadAnalyzer struct{}

ConfigLoadAnalyzer 配置加载错误分析器

func NewConfigLoadAnalyzer

func NewConfigLoadAnalyzer() *ConfigLoadAnalyzer

NewConfigLoadAnalyzer 创建配置加载错误分析器

func (*ConfigLoadAnalyzer) Analyze

func (a *ConfigLoadAnalyzer) Analyze(err error) *FailureReport

Analyze 分析错误并返回失败报告

func (*ConfigLoadAnalyzer) CanAnalyze

func (a *ConfigLoadAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查是否能分析该错误

type Conflict

type Conflict struct {
	StarterA string // 第一个 Starter
	StarterB string // 第二个 Starter
	Reason   string // 冲突原因
}

Conflict 表示两个 Starter 之间的冲突

func DetectConflicts

func DetectConflicts(starters []StarterModule) []Conflict

DetectConflicts 检测 Starter 之间的冲突

检测规则:

  1. 循环依赖检测
  2. 重复名称检测
  3. 缺失依赖检测

func (Conflict) String

func (c Conflict) String() string

String 返回冲突的可读描述信息。

type DuplicateBeanAnalyzer

type DuplicateBeanAnalyzer struct{}

DuplicateBeanAnalyzer 重复 Bean 错误分析器

func NewDuplicateBeanAnalyzer

func NewDuplicateBeanAnalyzer() *DuplicateBeanAnalyzer

NewDuplicateBeanAnalyzer 创建重复 Bean 错误分析器

func (*DuplicateBeanAnalyzer) Analyze

func (a *DuplicateBeanAnalyzer) Analyze(err error) *FailureReport

Analyze 分析错误并返回失败报告

func (*DuplicateBeanAnalyzer) CanAnalyze

func (a *DuplicateBeanAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查是否能分析该错误

type EventBusResult

type EventBusResult interface {
	Publish(event event.ApplicationEvent)
}

EventBusResult 事件总线访问接口。

type FailureAnalyzer

type FailureAnalyzer interface {
	// CanAnalyze 检查是否能分析该错误。
	CanAnalyze(err error) bool

	// Analyze 分析错误并返回失败报告。
	Analyze(err error) *FailureReport
}

FailureAnalyzer 失败分析器接口。

参考 Spring Boot 的 FailureAnalyzer。 在应用启动失败时提供友好的错误提示,帮助开发者快速定位问题。

type FailureAnalyzerRegistry

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

FailureAnalyzerRegistry 失败分析器注册表。

管理所有 FailureAnalyzer 的注册和查询。 分析时按注册顺序遍历,返回第一个匹配的失败报告。

func GlobalAnalyzerRegistry

func GlobalAnalyzerRegistry() *FailureAnalyzerRegistry

GlobalAnalyzerRegistry 返回全局失败分析器注册表

func NewFailureAnalyzerRegistry

func NewFailureAnalyzerRegistry() *FailureAnalyzerRegistry

NewFailureAnalyzerRegistry 创建失败分析器注册表

func (*FailureAnalyzerRegistry) Analyze

func (r *FailureAnalyzerRegistry) Analyze(err error) *FailureReport

Analyze 分析错误,返回第一个匹配的失败报告

func (*FailureAnalyzerRegistry) Register

func (r *FailureAnalyzerRegistry) Register(analyzer FailureAnalyzer)

Register 注册失败分析器

type FailureReport

type FailureReport struct {
	Headline          string         `json:"headline"`                    // 报告标题
	Description       string         `json:"description"`                 // 错误描述
	Action            string         `json:"action"`                      // 建议动作
	Cause             string         `json:"cause"`                       // 根因
	Details           map[string]any `json:"details,omitempty"`           // 附加详情
	StackTrace        string         `json:"stackTrace,omitempty"`        // 堆栈跟踪
	PossibleSolutions []string       `json:"possibleSolutions,omitempty"` // 可能的解决方案列表
}

FailureReport 失败报告。

参考 Spring Boot 的 FailureAnalysis,在应用启动失败时提供结构化的错误信息。 包含错误描述、建议动作、根因和可能的解决方案。

type LegacyBanner

type LegacyBanner = banner.LegacyBanner

type LegacyBannerOption added in v0.0.3

type LegacyBannerOption = banner.LegacyOption

LegacyBannerOption 是 banner.LegacyOption 的类型别名。

type Module

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

Module 可组合的配置单元。

Module 是 Go 风格的显式组合方式,替代全局 init() 注册。 每个 Module 可以独立测试、独立复用。

func ConditionalModule

func ConditionalModule(conds []condition.Condition, mod Module) Module

ConditionalModule 创建条件化模块

仅当所有条件匹配时,模块才会生效。

示例:

var RedisModule = boot.ConditionalModule(
    []condition.Condition{
        condition.OnProperty("cache.type", "redis"),
    },
    boot.Module{
        Beans: []boot.BeanProvider{
            boot.Provide(NewRedisClient),
        },
    },
)

func MergeModules

func MergeModules(modules ...Module) Module

MergeModules 合并多个模块为一个

示例:

var AppModule = boot.MergeModules(DatabaseModule, WebModule, CacheModule)

func NamedModule

func NamedModule(name string, mod Module) Module

NamedModule 创建带名称的模块

示例:

var DB = boot.NamedModule("database", boot.Module{
    Beans: []boot.BeanProvider{
        boot.Provide(NewDatabase),
    },
})

func (Module) Install

func (m Module) Install(c core.Container) error

Install 将模块的 Bean 注册到容器

func (Module) ModuleConditions

func (m Module) ModuleConditions() []condition.Condition

ModuleConditions 返回模块生效的条件

func (Module) ModuleHooks

func (m Module) ModuleHooks() []lifecycle.Hook

ModuleHooks 返回模块包含的生命周期钩子

func (Module) ModuleName

func (m Module) ModuleName() string

ModuleName 返回模块名称

func (Module) ModuleStarters

func (m Module) ModuleStarters() []Starter

ModuleStarters 返回模块包含的 Starter

type ModuleBuilder

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

ModuleBuilder 模块构建器,支持链式调用

func NewModule

func NewModule(args ...any) *ModuleBuilder

NewModule 创建模块(便捷构造函数)

支持两种调用方式:

  1. NewModule() - 返回构建器,支持链式调用
  2. NewModule(name, Bean(...), Starter(...)) - 直接创建模块

示例(链式调用):

var DBModule = boot.NewModule().
    Name("database").
    Bean(NewDatabase).
    Starter(&MigrationStarter{})

示例(直接创建):

var DBModule = boot.NewModule("database",
    boot.Bean(boot.Provide(NewDatabase)),
    boot.Starter(&MigrationStarter{}),
)

func (*ModuleBuilder) Bean

func (b *ModuleBuilder) Bean(provider BeanProvider) *ModuleBuilder

Bean 添加一个 Bean 提供者

func (*ModuleBuilder) Build

func (b *ModuleBuilder) Build() Module

Build 构建为 Module

func (*ModuleBuilder) Condition

Condition 添加一个条件

func (*ModuleBuilder) Conditions

func (b *ModuleBuilder) Conditions(conds ...condition.Condition) *ModuleBuilder

Conditions 添加多个条件

func (*ModuleBuilder) Hook

func (b *ModuleBuilder) Hook(hook lifecycle.Hook) *ModuleBuilder

Hook 添加一个生命周期钩子

func (*ModuleBuilder) Hooks

func (b *ModuleBuilder) Hooks(hooks ...lifecycle.Hook) *ModuleBuilder

Hooks 添加多个生命周期钩子

func (*ModuleBuilder) Install

func (b *ModuleBuilder) Install(c core.Container) error

Install 直接安装模块(便捷方法,无需先 Build)

func (*ModuleBuilder) Invoke

func (b *ModuleBuilder) Invoke(fn any) *ModuleBuilder

Invoke 添加一个安装时立即调用的函数

func (*ModuleBuilder) Module

func (b *ModuleBuilder) Module() Module

Module 将构建器转换为 Module(Build 的别名)

func (*ModuleBuilder) Name

func (b *ModuleBuilder) Name(name string) *ModuleBuilder

Name 设置模块名称

func (*ModuleBuilder) Starter

func (b *ModuleBuilder) Starter(s Starter) *ModuleBuilder

Starter 添加一个 Starter

type OrderPriority

type OrderPriority int

OrderPriority 定义自动配置执行顺序的优先级枚举。

值越小优先级越高,越先执行。 第三方插件集成时应参考此枚举设置 Order 值,确保正确的依赖顺序。

执行顺序设计原则

  1. 基础设施优先(日志、配置中心等)
  2. 数据层(数据库、缓存等)
  3. 安全层(认证、授权等)
  4. Web 层(HTTP 服务器、路由等)
  5. 业务层(定时任务、消息队列等)
  6. 监控层(Actuator、健康检查等)

完整依赖关系图

基础设施层 (-3000)
  └─ 日志 (Zerolog: -3000)
  └─ 配置中心

数据层 (-2000)
  └─ 数据库 (GORM: -2000)
  └─ 缓存 (Redis)
  └─ 对象存储

认证层 (-1500)
  └─ JWT 认证 (JWT: -1500)
  └─ OAuth2
  └─ LDAP

授权层 (-1300 ~ -1200)
  └─ Casbin GORM (CasbinGorm: -1300) ← 依赖 GORM,提供 GORM 版本的 Enforcer
  └─ Casbin 基础 (Casbin: -1200) ← 检测容器中是否有 Enforcer,有则使用,无则创建默认

安全核心层 (-100)
  └─ 安全框架 (Security: -100) ← 依赖认证和授权,构建完整安全体系

Web 层 (0)
  └─ HTTP 服务器
  └─ 路由
  └─ 中间件

业务层 (1000)
  └─ 定时任务 (Schedule: 1000)
  └─ 消息队列
  └─ 事件总线

监控层 (2000)
  └─ 指标收集 (Metrics: 2000)
  └─ Actuator (Actuator: 2000) ← 最后执行,监控所有组件

第三方插件集成指南

  • Redis 缓存: OrderPriorityDataLayer (-2000)
  • 消息队列: OrderPriorityBusinessLayer (1000)
  • 对象存储: OrderPriorityDataLayer (-2000)
  • 搜索引擎: OrderPriorityDataLayer (-2000)
  • 链路追踪: OrderPriorityMonitoringLayer (2000)
  • 指标收集: OrderPriorityMonitoringLayer (2000)
Example

ExampleOrderPriority 演示如何使用 OrderPriority 枚举设置执行顺序

package main

import (
	"fmt"

	"github.com/xudefa/enhance/boot"
	"github.com/xudefa/enhance/condition"
)

// ExampleOrderPriority 演示如何使用 OrderPriority 枚举设置执行顺序
func main() {
	// 基础设施层:日志组件(最先执行)
	boot.RegisterAutoConfigWith(&ExampleLoggerConfig{},
		boot.WithConditions(
			condition.OnProperty("log.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityInfrastructure)),
	)

	// 数据层:数据库组件
	boot.RegisterAutoConfigWith(&ExampleDatabaseConfig{},
		boot.WithConditions(
			condition.OnProperty("db.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityDataLayer)),
	)

	// 认证层:JWT 组件
	boot.RegisterAutoConfigWith(&ExampleJwtConfig{},
		boot.WithConditions(
			condition.OnProperty("security.jwt.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityAuthentication)),
	)

	// 授权层-GORM:Casbin GORM 适配器(依赖数据库)
	boot.RegisterAutoConfigWith(&ExampleCasbinGormConfig{},
		boot.WithConditions(
			condition.OnProperty("security.casbin.enabled", "true"),
			condition.OnProperty("security.casbin.policy-type", "gorm"),
		),
		boot.WithOrder(int(boot.OrderPriorityAuthorizationGorm)),
	)

	// 授权层:Casbin 基础配置(检测容器中是否有 Enforcer)
	boot.RegisterAutoConfigWith(&ExampleCasbinConfig{},
		boot.WithConditions(
			condition.OnProperty("security.casbin.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityAuthorization)),
	)

	// 安全核心层:安全过滤器链
	boot.RegisterAutoConfigWith(&ExampleSecurityConfig{},
		boot.WithConditions(
			condition.OnProperty("security.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPrioritySecurityCore)),
	)

	// Web 层:HTTP 服务器
	boot.RegisterAutoConfigWith(&ExampleWebConfig{},
		boot.WithConditions(
			condition.OnProperty("web.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityWebLayer)),
	)

	// 业务层:定时任务
	boot.RegisterAutoConfigWith(&ExampleScheduleConfig{},
		boot.WithConditions(
			condition.OnProperty("schedule.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityBusinessLayer)),
	)

	// 监控层:Actuator
	boot.RegisterAutoConfigWith(&ExampleActuatorConfig{},
		boot.WithConditions(
			condition.OnProperty("actuator.enabled", "true"),
		),
		boot.WithOrder(int(boot.OrderPriorityMonitoringLayer)),
	)

	fmt.Println("执行顺序: Infrastructure → DataLayer → Authentication → AuthorizationGorm → Authorization → SecurityCore → WebLayer → BusinessLayer → MonitoringLayer")
}

// 示例自动配置类(仅用于演示)

type ExampleLoggerConfig struct{}

func (c *ExampleLoggerConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleDatabaseConfig struct{}

func (c *ExampleDatabaseConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleJwtConfig struct{}

func (c *ExampleJwtConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleCasbinGormConfig struct{}

func (c *ExampleCasbinGormConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleCasbinConfig struct{}

func (c *ExampleCasbinConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleSecurityConfig struct{}

func (c *ExampleSecurityConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleWebConfig struct{}

func (c *ExampleWebConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleScheduleConfig struct{}

func (c *ExampleScheduleConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}

type ExampleActuatorConfig struct{}

func (c *ExampleActuatorConfig) Configure(ctx boot.ApplicationContext) error {
	return nil
}
Output:
执行顺序: Infrastructure → DataLayer → Authentication → AuthorizationGorm → Authorization → SecurityCore → WebLayer → BusinessLayer → MonitoringLayer
const (
	// OrderPriorityInfrastructure 基础设施层优先级 (-3000)
	// 适用于:日志、配置中心、环境变量等基础设施组件
	// 这些组件必须最先初始化,为其他组件提供基础能力
	OrderPriorityInfrastructure OrderPriority = -3000

	// OrderPriorityDataLayer 数据层优先级 (-2000)
	// 适用于:数据库、缓存、对象存储、搜索引擎等数据相关组件
	// 依赖基础设施层,为上层业务提供数据访问能力
	OrderPriorityDataLayer OrderPriority = -2000

	// OrderPriorityServiceDiscovery 服务发现层优先级 (-1800)
	// 适用于:Consul、Nacos、Eureka 等服务发现组件
	// 依赖基础设施层,为其他组件提供服务注册与发现能力
	OrderPriorityServiceDiscovery OrderPriority = -1800

	// OrderPriorityAuthentication 认证层优先级 (-1500)
	// 适用于:JWT、OAuth2、LDAP 等认证相关组件
	// 依赖数据层(可能需要从数据库加载用户信息)
	OrderPriorityAuthentication OrderPriority = -1500

	// OrderPriorityAuthorizationGorm 授权层-GORM 适配器优先级 (-1300)
	// 适用于:CasbinGorm 等基于数据库的授权适配器
	// 依赖数据层,在授权基础配置之前执行,提供数据库版本的 Enforcer
	OrderPriorityAuthorizationGorm OrderPriority = -1300

	// OrderPriorityAuthorization 授权层优先级 (-1200)
	// 适用于:Casbin、RBAC、ABAC 等授权相关组件
	// 依赖认证层和数据层(需要认证信息和权限数据)
	// 会检测容器中是否已有 Enforcer,有则使用,无则创建默认
	OrderPriorityAuthorization OrderPriority = -1200

	// OrderPrioritySecurityCore 安全核心层优先级 (-100)
	// 适用于:安全过滤器链、访问控制、加密等核心安全组件
	// 依赖认证和授权层,构建完整的安全体系
	OrderPrioritySecurityCore OrderPriority = -100

	// OrderPriorityWebLayer Web 层优先级 (0)
	// 适用于:HTTP 服务器、路由、中间件、Web 框架集成等
	// 依赖安全层,确保 Web 请求经过安全过滤
	OrderPriorityWebLayer OrderPriority = 0

	// OrderPriorityMiddleware 中间件层优先级 (100)
	// 适用于:限流器、CORS、压缩等 HTTP 中间件
	// 依赖 Web 层,在 Web 服务器启动前注册中间件
	OrderPriorityMiddleware OrderPriority = 100

	// OrderPriorityBusinessLayer 业务层优先级 (1000)
	// 适用于:定时任务、消息队列、事件总线、业务逻辑等
	// 依赖 Web 层和数据层,实现核心业务功能
	OrderPriorityBusinessLayer OrderPriority = 1000

	// OrderPriorityTaskLayer 任务层优先级 (-500)
	// 适用于:定时任务(Cron)、异步任务队列(Asynq)等任务调度组件
	// 依赖数据层,在业务层之前执行,为业务提供任务调度能力
	OrderPriorityTaskLayer OrderPriority = -500

	// OrderPriorityMonitoringLayer 监控层优先级 (2000)
	// 适用于:Actuator、健康检查、指标收集、链路追踪等
	// 最后初始化,监控所有其他组件的运行状态
	OrderPriorityMonitoringLayer OrderPriority = 2000
)

type PortInUseAnalyzer

type PortInUseAnalyzer struct{}

PortInUseAnalyzer 端口占用错误分析器

func NewPortInUseAnalyzer

func NewPortInUseAnalyzer() *PortInUseAnalyzer

NewPortInUseAnalyzer 创建端口占用错误分析器

func (*PortInUseAnalyzer) Analyze

func (a *PortInUseAnalyzer) Analyze(err error) *FailureReport

Analyze 分析错误并返回失败报告

func (*PortInUseAnalyzer) CanAnalyze

func (a *PortInUseAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查是否能分析该错误

type SimpleFailureAnalyzer

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

SimpleFailureAnalyzer 简单的失败分析器。

通过传入的分析函数创建分析器,适用于简单的错误分析场景。

func NewSimpleFailureAnalyzer

func NewSimpleFailureAnalyzer(analyzeFn func(err error) *FailureReport) *SimpleFailureAnalyzer

NewSimpleFailureAnalyzer 创建简单失败分析器

参数:

  • analyzeFn: 分析函数,接收错误返回失败报告,返回 nil 表示无法分析

func NewSimpleFailureAnalyzerWithCheck added in v0.0.4

func NewSimpleFailureAnalyzerWithCheck(checkFn func(err error) bool, analyzeFn func(err error) *FailureReport) *SimpleFailureAnalyzer

NewSimpleFailureAnalyzerWithCheck 创建带独立检查函数的简单失败分析器

参数:

  • checkFn: 轻量级检查函数,判断是否能分析该错误
  • analyzeFn: 分析函数,接收错误返回失败报告

func (*SimpleFailureAnalyzer) Analyze

func (s *SimpleFailureAnalyzer) Analyze(err error) *FailureReport

Analyze 使用分析函数分析错误。

func (*SimpleFailureAnalyzer) CanAnalyze

func (s *SimpleFailureAnalyzer) CanAnalyze(err error) bool

CanAnalyze 检查分析函数是否能处理该错误

type Starter

type Starter interface {
	// Name 返回启动器名称,用于依赖排序和日志输出。
	Name() string

	// Dependencies 返回依赖的其他启动器名称。
	// 启动器会按依赖关系拓扑排序后依次启动。
	Dependencies() []string

	// Configure 配置阶段调用,用于注册 Bean 和设置依赖。
	Configure(ctx ApplicationContext) error

	// Start 启动阶段调用,启动服务。
	Start(ctx ApplicationContext) error

	// Stop 停止阶段调用,释放资源。
	Stop(ctx ApplicationContext) error

	// GetCondition 返回启动条件,nil 表示始终启动。
	GetCondition() condition.Condition
}

Starter 应用启动器接口。

参考 Spring Boot 的 ApplicationRunner/CommandLineRunner。 每个集成的 Starter 管理其自身的生命周期,包括配置、启动和停止。

生命周期:

  • Configure: 在配置阶段调用,用于注册 Bean 和设置依赖
  • Start: 在就绪阶段调用,启动服务(如 HTTP 服务器)
  • Stop: 在停止阶段调用,释放资源(逆序执行)

type StarterModule

type StarterModule struct {
	Name         string   // Starter 名称
	Dependencies []string // 依赖的其他 Starter 名称
	Optional     bool     // 是否为可选依赖
}

StarterModule 模块化的 Starter 定义

用于声明模块的依赖关系和可选性,支持冲突检测。

func CompositeStarter

func CompositeStarter(starters ...StarterModule) StarterModule

CompositeStarter 创建组合 Starter

将多个 Starter 组合成一个逻辑单元,便于模块化声明。 示例:

var WebStarter = boot.CompositeStarter(
    HTTPStarter,
    ValidationStarter,
    ExceptionStarter,
)

func ResolveDependencies

func ResolveDependencies(starters []StarterModule) ([]StarterModule, error)

ResolveDependencies 解析并排序 Starter 依赖

返回按依赖关系排序的 Starter 列表。

type StarterRegistry

type StarterRegistry interface {
	// Register 注册一个 Starter 到注册表。
	Register(starter Starter)

	// Get 根据名称获取已注册的 Starter,未找到返回 nil。
	Get(name string) Starter

	// GetAll 获取所有已注册的 Starter(返回副本)。
	GetAll() []Starter

	// GetOrdered 按依赖关系拓扑排序获取 Starter。
	// 如果存在循环依赖,回退到原始注册顺序。
	GetOrdered() []Starter
}

StarterRegistry 启动器注册表接口。

管理所有 Starter 的注册和依赖排序。 使用 Kahn 算法进行拓扑排序,确保依赖的启动器先启动。

func GlobalStarterRegistry

func GlobalStarterRegistry() StarterRegistry

GlobalStarterRegistry 返回全局启动器注册表。

func NewStarterRegistry

func NewStarterRegistry() StarterRegistry

NewStarterRegistry 创建启动器注册表。

返回 StarterRegistry 接口,隐藏实现细节。

type StarterRegistryStruct added in v0.0.3

type StarterRegistryStruct = starterRegistryImpl

StarterRegistryStruct 是 starterRegistryImpl 实现类型的别名。

在重构前 StarterRegistry 是一个结构体,现在改为接口。 此别名保留对底层实现类型的访问,便于需要类型断言的场景。

type TextBanner

type TextBanner = banner.TextBanner

Directories

Path Synopsis
Package banner 提供启动横幅功能,用于 enhance 框架。
Package banner 提供启动横幅功能,用于 enhance 框架。
Package failure 提供应用启动失败分析功能,用于 enhance 框架。
Package failure 提供应用启动失败分析功能,用于 enhance 框架。

Jump to

Keyboard shortcuts

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