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

Spring Boot Kotlin异步方法未生效问题排查求助

Spring Boot Kotlin异步方法不生效问题排查

核心问题:手动实例化Bean,绕过Spring代理

你的测试代码存在致命错误:在hello()方法中手动创建了HelloAsync实例,覆盖了Spring注入的Bean:

helloAsync = HelloAsync()

Spring的@Async功能依赖AOP代理实现,只有从Spring容器中获取的代理Bean才会触发异步逻辑。手动new的对象不受Spring管理,@Async注解完全失效,导致所有调用都同步执行在主线程。

修正测试代码

删除手动实例化的代码,直接使用Spring注入的helloAsync Bean,同时测试类需要添加@SpringBootTest启动Spring上下文:

package com.rifqi.jsnowball

import com.rifqi.jsnowball.service.HelloAsync
import org.junit.jupiter.api.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest

@SpringBootTest
class HelloAsyncTest {
    @Autowired
    private lateinit var helloAsync: HelloAsync

    private val log: Logger = LoggerFactory.getLogger(this.javaClass)

    @Test
    fun hello() {
        for (i in 0..9) {
            helloAsync.helloWorld()
        }
        log.info("After calling hello()")
        Thread.sleep(5000)
    }
}

额外注意事项

  • 移除测试类的@EnableAsync:你的AsyncConfig已经标注@EnableAsync,全局生效即可,无需在测试类重复添加。
  • 日志无需Spring注入:原测试类中log使用@Autowired是错误的,Logger直接初始化即可。

修正后预期效果

执行测试后,日志会显示不同的线程名称(如task-1、task-2),说明异步线程池在工作,总耗时会接近2秒(线程池并行处理任务),而非同步执行的20秒。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:52:52