You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Kotlin DSL中获取指定类型所有Bean并执行初始化逻辑

解决Spring上下文初始化后执行所有Yoyo类型Bean逻辑的方案

嘿,这个需求在Spring里有好几种简单的实现方式,我给你列几个适配你Kotlin代码的常用方案:

方案一:用CommandLineRunner(SpringBoot推荐)

这是SpringBoot里最常用的启动后执行逻辑的方式,Spring会在上下文完全初始化完成后自动调用它的run方法,而且能直接注入所有Yoyo类型的Bean列表,非常方便:

@Component
class YoyoInitializer(private val yoyos: List<Yoyo>) : CommandLineRunner {
    override fun run(vararg args: String?) {
        // 遍历所有Yoyo Bean执行haha()方法
        yoyos.forEach { it.haha() }
    }
}

说明:Spring会自动把容器中所有Yoyo类型的Bean收集到List<Yoyo>里注入进来,不需要额外配置,直接遍历执行逻辑即可。如果你的实现类重写了haha()方法,会自动执行各自的重写逻辑。

方案二:监听ContextRefreshedEvent事件

如果你需要更精准地监听上下文初始化完成的时机,可以通过Spring的事件机制来实现:

@Component
class YoyoContextListener : ApplicationListener<ContextRefreshedEvent> {
    override fun onApplicationEvent(event: ContextRefreshedEvent) {
        // 获取Spring上下文
        val context = event.applicationContext
        // 过滤出所有Yoyo类型的Bean
        val yoyos = context.getBeansOfType(Yoyo::class.java).values
        yoyos.forEach { it.haha() }
        
        // 注意:如果存在父子上下文(比如SpringMVC的场景),这个事件会触发多次,可加判断过滤:
        // if (context.parent == null) {
        //     yoyos.forEach { it.haha() }
        // }
    }
}

说明:ContextRefreshedEvent会在Spring上下文所有Bean实例化并初始化完成后触发,适合需要感知上下文生命周期的场景。

方案三:在main方法中直接获取上下文处理

如果你想在启动代码里直接处理,也可以直接拿到初始化完成的上下文,然后获取Bean执行逻辑:

@SpringBootApplication
class YoyoApp

fun main(args: Array<String>) {
    // 启动Spring应用并获取上下文
    val context = SpringApplicationBuilder()
        .sources(YoyoApp::class.java)
        .run(*args)
    
    // 上下文初始化完成后,执行逻辑
    val yoyos = context.getBeansOfType(Yoyo::class.java).values
    yoyos.forEach { it.haha() }
}

说明:run方法返回的就是已经完全初始化好的Spring上下文,直接在这里处理最直接,适合简单场景。

内容的提问来源于stack exchange,提问作者maslick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:19:00