From 4ad6bc87783e71801758d355d5e749e006df3050 Mon Sep 17 00:00:00 2001 From: ForteScarlet Date: Mon, 10 Jun 2024 23:08:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0Application=E7=9A=84=E9=83=A8?= =?UTF-8?q?=E5=88=86=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Writerside/topics/basic-application.md | 93 ++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/Writerside/topics/basic-application.md b/Writerside/topics/basic-application.md index ec65976..2989628 100644 --- a/Writerside/topics/basic-application.md +++ b/Writerside/topics/basic-application.md @@ -161,3 +161,96 @@ var application = Applications.launchApplicationBlocking(Simple.INSTANCE, appCon ## Bot的注册 有关Bot注册的相关描述可前往 [Bot管理器](BotManager.md) 章节阅读。 + +## Spring中获取Application + +如果你在使用 Spring Boot starter,那么你可以直接通过bean注入的方式得到 `Application` 实例。 + + + + +```Kotlin +@Component +class MyComponent +@Autowired // 其实注解可以省略,这里只是为了让'注入'行为比较显眼儿 +constructor( + private val application: Application // 构造注入 Application + +) { + // ... +} +``` + + + + +```Java +@Component +public class MyComponent { + private final Application application; + + @Autowired // 其实注解可以省略,这里只是为了让'注入'行为比较显眼儿 + public MyComponent(Application application) { // 构造注入 Application + this.application = application; + } + + // ... +} +``` + + + + +你也可以基于此间接地获取 `BotManager`、`Bot` 等其他信息。 + + + + +```Kotlin +@Component +class MyComponent( + private val application: Application +) { + // 假设这里是个定时任务 + // 或者其他什么跟事件没关系的地方 + fun runTask() { + // 得到所有的BotManager并遍历 + for (botManager in application.botManagers) { + // ... + // 得到每一个BotManager中的所有已注册且未被关闭的Bot并遍历 + for (bot in botManager.all()) { + // ... + } + } + } +} +``` + + + + +```Java +@Component +public class MyComponent { + private final Application application; + + public MyComponent(Application application) { + this.application = application; + } + + public void runTask() { + // 得到所有的BotManager并遍历 + for (var botManager : application.getBotManagers()) { + // ... + // 得到每一个BotManager中的所有已注册且未被关闭的Bot并遍历 + for (var it = botManager.all().iterator(); it.hasNext(); ) { + var bot = it.next(); + // ... + } + } + } +} +``` + + + \ No newline at end of file