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

Spring Boot中如何注册非静态Logger Bean并注入控制器使用?

在Spring Boot中实现Logger的依赖注入(非静态方式)

一、注册Logger Bean

要让Spring支持Logger的依赖注入,需要在容器中注册一个原型作用域的Logger Bean,确保每个类能获取到对应自身类名的Logger实例:

通过配置类注册

创建一个@Configuration类,利用InjectionPoint获取注入目标的类信息,生成对应的Logger:

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.InjectionPoint
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope

@Configuration
class LoggerConfig {

    @Bean
    @Scope("prototype")
    fun logger(injectionPoint: InjectionPoint): Logger {
        val targetClass = injectionPoint.methodParameter?.containingClass 
            ?: injectionPoint.field?.declaringClass 
            ?: throw IllegalArgumentException("无法确定注入目标类")
        return LoggerFactory.getLogger(targetClass)
    }
}
  • 用prototype作用域是因为每个类的Logger实例是独立的,对应各自的类名,避免日志输出的类名错误。
  • InjectionPoint能帮我们拿到当前需要注入Logger的类,确保生成的Logger是对应类的实例。

二、控制器中依赖注入Logger

你提供的控制器代码已经符合构造注入的规范,只需修复$id未定义的问题即可正常使用:

import org.slf4j.Logger
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class SecondController(
    private val logger: Logger, // 构造注入Logger实例
) {

    @GetMapping("/logger")
    fun logger() {
        val id = 123 // 示例:可替换为实际业务中的ID(如请求参数、路径变量)
        logger.info("id $id")
    }
}

三、注意事项

  • 构造注入优先:Spring官方推荐构造注入,能保证依赖不可变且完全初始化,避免空指针风险。
  • 默认日志框架支持:Spring Boot默认集成SLF4J+Logback,无需额外引入依赖,直接注入org.slf4j.Logger即可。
  • 避免单例Logger Bean:如果注册单例的Logger,所有类会共用同一个Logger(对应配置类的类名),导致日志输出的类名不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:07:33