AstraTemplate
一款生产级的 Minecraft 插件/模组模板,使用 Kotlin 编写。提供了一个模块化、生命周期驱动的架构,可在 Paper、Forge 和 NeoForge 上从单一共享代码库运行。
基于此模板构建的插件
项目结构
AstraTemplate/
├── instances/
│ ├── bukkit/ ← Paper 入口点 + 平台适配层
│ ├── forge/ ← Forge 入口点 + 平台适配层
│ └── neoforge/ ← NeoForge 入口点 + 平台适配层
└── modules/
├── api/
│ ├── local/ ← 数据库 (Exposed ORM, 跨平台无关)
│ └── remote/ ← REST 客户端 (Ktor, 跨平台无关)
├── core/ ← 配置、翻译、协程作用域
├── build-konfig/ ← 编译时常量(id、版本等)
├── feature-command/ ← 所有命令(跨平台无关!)
├── feature-gui/
│ ├── api/ ← GUI 接口(Router、GuiModule)
│ └── bukkit/ ← Bukkit 箱式 GUI 实现
└── feature-event/
├── bukkit/ ← Bukkit 事件监听器
├── forge/ ← Forge 事件监听器
└── neoforge/ ← NeoForge 事件监听器
每个 instances/<platform> 都通过 ShadowJar 构建胖 JAR 包,且是唯一定义特定平台的模块。modules/ 中的所有模块要么完全跨平台无关,要么拥有明确命名的平台变体。
模块
modules/core — 配置、翻译、协程作用域
这是其他所有模块依赖的基础。提供:
- Config —
PluginConfiguration 是一个 @Serializable 数据类,写入到 config.yml。通过 StateFlowKrate 在 /atempreload 时重载。
- Translations —
PluginTranslation 以相同的方式与 translation.yml 配合工作。每个字符串都有默认值,因此即使没有配置文件,插件也能开箱即用。
- Coroutine scopes —
ioScope、mainScope 和 unconfinedScope 由 KotlinDispatchers 支持(这是对 Dispatchers.IO / 主线程等的平台抽象)。所有作用域都会在 onDisable 时被取消。
modules/api/local — 通过 Exposed ORM 访问本地数据库
通过 Jetbrains Exposed ORM 进行本地数据库访问。LocalDao 接口为 UserTable 和 UserRatingTable 暴露了用于 CRUD 操作的挂起函数。底层数据库连接从配置流中反应式派生,因此从 H2 切换到 MySQL 只需更改一行配置并重新加载即可。
支持的驱动(在 libs.versions.toml 中配置):H2、SQLite、MySQL、MariaDB。
modules/api/remote — 通过 Ktor 构建的 REST API 客户端
使用 Ktor 构建的 REST API 客户端。演示了如何从外部 HTTP 端点(Rick & Morty API)获取数据。RickMortyApi 接口返回 Result<T> — 错误永远不会抛出,而是始终显式返回。
modules/build-konfig — 编译时常量
通过 BuildConfig Gradle 插件生成编译时常量(id、version 等)。从需要引用插件身份的任何模块中导入,而无需在运行时硬编码字符串。
modules/feature-command — 跨平台命令(无平台导入)
所有命令集中在一个地方,且没有平台导入。使用来自 AstraLibs 的 Brigadier DSL 定义命令,这些命令可以在 Paper、Forge 和 NeoForge 上编译并以相同方式运行。平台特定的 MultiplatformCommand 适配器在 RootModule 级别注入。
modules/feature-gui — 箱式 GUI(Bukkit,其他平台有存根)
分为 api(Router 接口 + GuiModule)和 bukkit(实现部分)。Bukkit 实现提供了由 StateFlow 驱动的页式箱子库存——当底层数据发生变化时,GUI 会自动重新渲染。在 Forge/NeoForge 上,StubGuiModule 满足接口要求,从而使共享的命令模块能够在不引入 Bukkit 的情况下编译。
modules/feature-event — 平台特定事件监听器
平台特定的事件监听器,每个平台对应一个子模块。Bukkit 变体监听 BlockPlaceEvent;Forge 和 NeoForge 变体监听服务器刻。每个子模块都暴露了一个 Lifecycle,以便 RootModule 能够干净地注册和注销监听器。
架构
生命周期树
每个模块都暴露一个带有三个回调的 Lifecycle:onEnable、onDisable、onReload。插件入口点创建 RootModule,链接所有子生命周期,并将它们委托给自身:
// instances/bukkit — AstraTemplate.kt
class AstraTemplate : LifecyclePlugin() {
private val rootModule = RootModule(this)
```kotlin
override fun onEnable() = rootModule.lifecycle.onEnable()
override fun onDisable() = rootModule.lifecycle.onDisable()
override fun onReload() = rootModule.lifecycle.onReload()
}
// instances/bukkit — RootModule.kt
class RootModule(plugin: AstraTemplate) {
val coreModule = CoreModule(plugin.dataFolder, DefaultBukkitDispatchers(plugin))
val apiLocalModule = ApiLocalModule(coreModule.configKrate.cachedStateFlow, coreModule.ioScope)
val apiRemoteModule = ApiRemoteModule()
val eventModule = EventModule(coreModule, plugin)
val guiModule = BukkitGuiModule(coreModule, apiLocalModule)
val commandModule = CommandModule(coreModule, apiRemoteModule, guiModule, ...)
val lifecycle = Lifecycle.Lambda(
onEnable = { listOf(coreModule, eventModule, apiLocalModule, commandModule).forEach(Lifecycle::onEnable) },
onDisable = { /* 相同列表,反向执行 */ },
onReload = { /* 相同列表 */ }
)
}
这使得插件支持运行时重载——/atempreload 会按相反顺序遍历相同的链并重新启用它,从而即时捕获任何配置或翻译更改。
graph TD
Plugin --> RootModule
RootModule --> CoreModule
RootModule --> ApiLocalModule
RootModule --> ApiRemoteModule
RootModule --> EventModule
RootModule --> CommandModule
EventModule --> TemplateEvent
EventModule --> BetterAnotherEvent
依赖注入
这里没有使用 DI(依赖注入)框架。每个模块都是普通类,其构造函数接收它所依赖的其他模块接口。RootModule 是组合根入口,以正确的顺序实例化所有内容,并在需要延迟初始化时使用 lazy {}。
// 传递整个模块接口,而不是从中提取的单个服务
val commandModule = CommandModule(
coreModule = coreModule,
guiModule = guiModule,
apiRemoteModule = apiRemoteModule,
...
)
这保持了耦合关系的显式性,并避免了因缺少绑定而导致的隐藏运行时故障。
跨平台命令
命令位于 modules/feature-command 中——这是一个纯 Kotlin 模块,具有零平台依赖。它们使用来自 AstraLibs 的 Brigadier DSL,该 DSL 抽象了 Paper 和 Forge 的原生 Brigadier 适配器。
// 在 Paper、Forge 和 NeoForge 上无需任何更改即可工作
command("rickandmorty") {
literal("random") {
runs { ctx ->
scope.launch(dispatchers.IO) {
rmApi.getRandomCharacter(Random.nextInt(0, 100))
.onSuccess { ctx.getSender().sendMessage(...) }
.onFailure { ctx.getSender().sendMessage(...) }
}
}
}
literal("specific") {
argument("number", IntegerArgumentType.integer()) { numberArg ->
runs { ctx -> send(ctx.getSender(), ctx.requireArgument(numberArg)) }
}
}
}
在每个平台上,RootModule 提供一个由相应适配器支持的 MultiplatformCommand(PaperMultiplatformCommands、MinecraftMultiplatformCommands)。共享的命令代码永远不需要更改。
可用命令
| 命令 |
描述 |
/add <player> <material> [amount] |
向玩家物品栏添加物品 |
/translation |
显示当前翻译值(重载后很有用) |
/adamage <player> <amount> |
对玩家造成伤害 |
/atempgui |
打开示例分页 GUI |
/rickandmorty random |
通过 REST 获取随机的瑞克和莫蒂角色 |
/rickandmorty specific <id> |
通过 ID 获取特定角色 |
/atempreload |
重载配置、翻译和数据库连接 |
配置
配置和翻译是普通的 @Serializable 数据类,通过 kaml 序列化为 YAML。内联文档注释会直接渲染在生成的 YAML 文件中:
@Serializable
data class PluginConfiguration(
@YamlComment("config1 的第一行描述", "config2 的第二行描述")
@SerialName("config_1")
val config1: String = "NONE",
@SerialName("database")
val database: DatabaseConfiguration = DatabaseConfiguration.H2("db")
)
配置和翻译都存储为 StateFlowKrate / CachedKrate。任何读取它们的模块在重载后总是能看到最新值——无需手动传播。
本地数据库
modules/api/local 使用 Jetbrains Exposed 作为 ORM。数据库连接从配置流中响应式地派生而来——当使用新的数据库 URL 重载配置时,连接会自动替换:
private val databaseFlow = configFlow
.map { it.database }
.distinctUntilChanged()
.flatMapLatest { configuration -> configuration.connectAsFlow() }
.onEach { db ->
transaction(db) { SchemaUtils.create(UserRatingTable, UserTable) }
}
.shareIn(ioScope, SharingStarted.Eagerly, 1)
支持的驱动程序(在 libs.versions.toml 中替换):H2、SQLite、MySQL、MariaDB。
远程 API
modules/api/remote 展示了如何使用 Ktor 调用外部 REST 端点。接口非常简洁:
interface RickMortyApi {
suspend fun getRandomCharacter(id: Int): Result<RMResponse>
}
错误以 Result<T> 形式返回——绝不会抛出异常——因此调用者可以显式处理失败情况。
GUI (Bukkit)
GUI 层位于 modules/feature-gui/api 中定义的 Router 接口之后。Bukkit 实现提供了带有 Kotlin StateFlow 响应式状态的分页箱子库存:
SampleGuiComponent 拥有状态(Loading / Items / Users)
SampleGUI 观察状态并在每次发射时重新渲染
- 导航(下一页/上一页、更改模式、添加用户、返回/关闭)由专用的按钮对象处理
在 Forge/NeoForge 上,StubGuiModule 实现了 GuiModule 接口,以便共享的 CommandModule 无需依赖 Bukkit 即可编译。
构建
# Paper 插件
./gradlew :instances:bukkit:shadowJar
# Forge 模组
./gradlew :instances:forge:shadowJar
# NeoForge 模组
./gradlew :instances:neoforge:shadowJar
# 运行所有测试
./gradlew allTests
输出的 JAR 文件位于各实例的 build/libs/ 目录中,并可通过 FTP Gradle 插件选择性地复制到远程服务器(在 libs.versions.toml 中配置目标地址)。
测试服务器(Docker)
项目根目录下的 docker-compose.yml 使用 itzg/minecraft-server 启动本地测试服务器。
运行前,请手动编辑 docker-compose.yml,取消注释目标平台(Forge、NeoForge 或 Paper)对应的代码块,并注释掉其他代码块。每个代码块设置了 TYPE、VERSION 以及平台特定的版本变量,其下方还有匹配的 volumes 条目。
docker compose up
AstraTemplate
A production-grade Minecraft plugin/mod template written in Kotlin. Provides a modular, lifecycle-driven architecture that runs across Paper, Forge, and NeoForge from a single shared codebase.
Plugins built on this template
Project structure
AstraTemplate/
├── instances/
│ ├── bukkit/ ← Paper entry point + platform wiring
│ ├── forge/ ← Forge entry point + platform wiring
│ └── neoforge/ ← NeoForge entry point + platform wiring
└── modules/
├── api/
│ ├── local/ ← Database (Exposed ORM, platform-agnostic)
│ └── remote/ ← REST client (Ktor, platform-agnostic)
├── core/ ← Config, translations, coroutine scopes
├── build-konfig/ ← Compile-time constants (id, version, etc.)
├── feature-command/ ← All commands (platform-agnostic!)
├── feature-gui/
│ ├── api/ ← GUI interfaces (Router, GuiModule)
│ └── bukkit/ ← Bukkit chest-GUI implementation
└── feature-event/
├── bukkit/ ← Bukkit event listeners
├── forge/ ← Forge event listeners
└── neoforge/ ← NeoForge event listeners
Each instances/<platform> builds a fat jar via ShadowJar and is the only place that knows about a specific platform. Everything in modules/ is either fully platform-agnostic or has a clearly named platform variant.
Modules
modules/core — config, translations, coroutine scopes
The foundation every other module depends on. Provides:
- Config —
PluginConfiguration is a @Serializable data class written to config.yml. Reloaded on /atempreload via StateFlowKrate.
- Translations —
PluginTranslation works the same way with translation.yml. Every string has a default value so the plugin works out of the box with no files present.
- Coroutine scopes —
ioScope, mainScope, and unconfinedScope backed by KotlinDispatchers (platform-provided abstraction over Dispatchers.IO / main thread / etc.). All scopes are cancelled in onDisable.
modules/api/local — local database via Exposed ORM
Local database access via Jetbrains Exposed ORM. The LocalDao interface exposes suspend functions for CRUD operations on UserTable and UserRatingTable. The underlying database connection is derived reactively from the config flow, so switching from H2 to MySQL is a one-line config change and a reload.
Supported drivers (configured in libs.versions.toml): H2, SQLite, MySQL, MariaDB.
modules/api/remote — REST API client via Ktor
REST API client built with Ktor. Demonstrates fetching data from an external HTTP endpoint (the Rick & Morty API). The RickMortyApi interface returns Result<T> — errors are never thrown, always returned explicitly.
modules/build-konfig — compile-time constants
Generates compile-time constants (id, version, etc.) via the BuildConfig Gradle plugin. Import from any module that needs to reference the plugin's identity at runtime without hardcoding strings.
modules/feature-command — cross-platform commands (no platform imports)
All commands in one place, with no platform imports. Uses the Brigadier DSL from AstraLibs to define commands that compile and run identically on Paper, Forge, and NeoForge. The platform-specific MultiplatformCommand adapter is injected at the RootModule level.
modules/feature-gui — chest GUI (Bukkit, with stub for other platforms)
Split into api (the Router interface + GuiModule) and bukkit (the implementation). The Bukkit implementation provides a paginated chest inventory driven by StateFlow — the GUI re-renders automatically whenever the underlying data changes. On Forge/NeoForge a StubGuiModule satisfies the interface so the shared command module compiles without pulling in Bukkit.
modules/feature-event — platform-specific event listeners
Platform-specific event listeners, one submodule per platform. The Bukkit variant listens to BlockPlaceEvent; Forge and NeoForge variants listen to the server tick. Each submodule exposes a Lifecycle so RootModule can register and unregister listeners cleanly.
Architecture
Lifecycle tree
Every module exposes a Lifecycle with three callbacks: onEnable, onDisable, onReload. The plugin entry point creates a RootModule, chains all child lifecycles, and delegates to them:
// instances/bukkit — AstraTemplate.kt
class AstraTemplate : LifecyclePlugin() {
private val rootModule = RootModule(this)
override fun onEnable() = rootModule.lifecycle.onEnable()
override fun onDisable() = rootModule.lifecycle.onDisable()
override fun onReload() = rootModule.lifecycle.onReload()
}
// instances/bukkit — RootModule.kt
class RootModule(plugin: AstraTemplate) {
val coreModule = CoreModule(plugin.dataFolder, DefaultBukkitDispatchers(plugin))
val apiLocalModule = ApiLocalModule(coreModule.configKrate.cachedStateFlow, coreModule.ioScope)
val apiRemoteModule = ApiRemoteModule()
val eventModule = EventModule(coreModule, plugin)
val guiModule = BukkitGuiModule(coreModule, apiLocalModule)
val commandModule = CommandModule(coreModule, apiRemoteModule, guiModule, ...)
val lifecycle = Lifecycle.Lambda(
onEnable = { listOf(coreModule, eventModule, apiLocalModule, commandModule).forEach(Lifecycle::onEnable) },
onDisable = { /* same list, reversed */ },
onReload = { /* same list */ }
)
}
This makes the plugin reloadable at runtime — /atempreload walks the same chain in reverse and re-enables it, picking up any config or translation changes on the fly.
graph TD
Plugin --> RootModule
RootModule --> CoreModule
RootModule --> ApiLocalModule
RootModule --> ApiRemoteModule
RootModule --> EventModule
RootModule --> CommandModule
EventModule --> TemplateEvent
EventModule --> BetterAnotherEvent
Dependency injection
There is no DI framework. Each module is a plain class whose constructor receives other module interfaces it depends on. RootModule is the composition root and instantiates everything in the right order, using lazy {} where initialization must be deferred.
// Pass the whole module interface, not individual services extracted from it
val commandModule = CommandModule(
coreModule = coreModule,
guiModule = guiModule,
apiRemoteModule = apiRemoteModule,
...
)
This keeps coupling explicit and avoids hidden runtime failures from missing bindings.
Cross-platform commands
Commands live in modules/feature-command — a plain Kotlin module with zero platform dependencies. They use the Brigadier DSL from AstraLibs, which abstracts over Paper's and Forge's native Brigadier adapters.
// Works on Paper, Forge, and NeoForge without any changes
command("rickandmorty") {
literal("random") {
runs { ctx ->
scope.launch(dispatchers.IO) {
rmApi.getRandomCharacter(Random.nextInt(0, 100))
.onSuccess { ctx.getSender().sendMessage(...) }
.onFailure { ctx.getSender().sendMessage(...) }
}
}
}
literal("specific") {
argument("number", IntegerArgumentType.integer()) { numberArg ->
runs { ctx -> send(ctx.getSender(), ctx.requireArgument(numberArg)) }
}
}
}
On each platform the RootModule provides a MultiplatformCommand backed by the right adapter (PaperMultiplatformCommands, MinecraftMultiplatformCommands). The shared command code never needs to change.
Available commands
| Command |
Description |
/add <player> <material> [amount] |
Add item to a player's inventory |
/translation |
Show current translation value (useful after reload) |
/adamage <player> <amount> |
Deal damage to a player |
/atempgui |
Open the sample paginated GUI |
/rickandmorty random |
Fetch a random Rick & Morty character via REST |
/rickandmorty specific <id> |
Fetch a specific character by id |
/atempreload |
Reload config, translations, and database connection |
Configuration
Config and translations are plain @Serializable data classes serialized to YAML via kaml. Inline doc-comments render directly in the generated YAML file:
@Serializable
data class PluginConfiguration(
@YamlComment("First line description for config1", "Second line description for config2")
@SerialName("config_1")
val config1: String = "NONE",
@SerialName("database")
val database: DatabaseConfiguration = DatabaseConfiguration.H2("db")
)
Both config and translations are stored as StateFlowKrate / CachedKrate. Any module that reads them always sees the latest value after a reload — no manual propagation needed.
Local database
modules/api/local uses Jetbrains Exposed as the ORM. The database connection is derived reactively from the config flow — when the config is reloaded with a new database URL, the connection is replaced automatically:
private val databaseFlow = configFlow
.map { it.database }
.distinctUntilChanged()
.flatMapLatest { configuration -> configuration.connectAsFlow() }
.onEach { db ->
transaction(db) { SchemaUtils.create(UserRatingTable, UserTable) }
}
.shareIn(ioScope, SharingStarted.Eagerly, 1)
Supported drivers (swap in libs.versions.toml): H2, SQLite, MySQL, MariaDB.
Remote API
modules/api/remote shows how to call an external REST endpoint using Ktor. The interface is minimal:
interface RickMortyApi {
suspend fun getRandomCharacter(id: Int): Result<RMResponse>
}
Errors are returned as Result<T> — never thrown — so callers handle failures explicitly.
GUI (Bukkit)
The GUI layer sits behind a Router interface defined in modules/feature-gui/api. The Bukkit implementation provides a paginated chest inventory with reactive state via Kotlin StateFlow:
SampleGuiComponent owns state (Loading / Items / Users)
SampleGUI observes state and re-renders on every emission
- Navigation (next/prev page, change mode, add user, back/close) is handled by dedicated button objects
On Forge/NeoForge a StubGuiModule satisfies the GuiModule interface so the shared CommandModule compiles without a Bukkit dependency.
Building
# Paper plugin
./gradlew :instances:bukkit:shadowJar
# Forge mod
./gradlew :instances:forge:shadowJar
# NeoForge mod
./gradlew :instances:neoforge:shadowJar
# Run all tests
./gradlew allTests
Output jars land in each instance's build/libs/ directory and are optionally copied to a remote server by the FTP Gradle plugin (configure the destination in libs.versions.toml).
Test server (Docker)
docker-compose.yml at the project root starts a local test server using itzg/minecraft-server.
Before running, manually edit docker-compose.yml to uncomment the block for your target platform (Forge, NeoForge, or Paper) and comment out the others. Each block sets the TYPE, VERSION, and platform-specific version variables, and the matching volumes entry below it.
docker compose up
评论 0
登录后参与评分
还没有评论,来抢沙发吧