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

如何在Spring函数式Bean定义DSL中获取InjectionPoint实现Logger注入

我们使用Bean工厂函数实现将Logger对象注入到业务Bean中,该实现逻辑与Simar Paul Singh在其文章《Inject loggers in Spring》中介绍的方案类似。

import org.slf4j.*
import org.springframework.beans.factory.InjectionPoint
import org.springframework.context.annotation.*

@Bean
@Scope("prototype")
fun logger(injectionPoint: InjectionPoint): Logger {
  return LoggerFactory.getLogger(
      injectionPoint.methodParameter?.containingClass // 构造函数注入场景
          ?: injectionPoint.field?.declaringClass // 字段注入场景
  )
}

近日我尝试将上述Bean声明转换为使用Spring函数式Bean定义DSL的写法,但是始终无法获取到对应的InjectionPoint实例来定位Logger需要注入的目标类。

import org.slf4j.*
import org.springframework.beans.factory.InjectionPoint
import org.springframework.context.support.beans
import org.springframework.context.support.BeanDefinitionDsl.Scope.PROTOTYPE

fun beans() = beans {
    bean(scope = PROTOTYPE) {
        val injectionPoint = ref<InjectionPoint>()
    
        LoggerFactory.getLogger(
            injectionPoint.methodParameter?.containingClass // 构造函数注入场景
                ?: injectionPoint.field?.declaringClass // 字段注入场景
        )
    }
}

上述代码运行后会抛出如下异常:

NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.beans.factory.InjectionPoint' available

请问有没有方案可以在DSL写法中获取到InjectionPoint实例,或者至少获取到注入目标类,实现和非DSL Bean声明一致的Logger注入能力?
最小复现代码仓库已上传至GitHub,可在项目根目录执行./gradlew bootRun(Windows系统执行.\gradlew.bat bootRun)复现错误。

我已经在Spring官方GitHub仓库提交了相关Issue:issue #27738


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:36:02