如何在静态方法中使用spring bean?

问题描述 投票:0回答:1

我有这样的配置,我定义了

headerHolder
bean。但现在不可能在静态方法中使用它,因为在这种情况下我总是有
anonymousUserId
字段等于
null
。但同时,当使用自动装配时,它就充满了价值。为什么会这样呢?我该如何解决它?

@Configuration
class HeaderInterceptorConfig : WebMvcConfigurer {
    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(anonymousUserIdInterceptor())
    }

    @Bean
    fun anonymousUserIdInterceptor(): HeaderInterceptor {
        return HeaderInterceptor(headerHolder())
    }

    @Bean
    @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    fun headerHolder(): HeaderHolder {
        return HeaderHolder()
    }
}

open class HeaderHolder(
    var anonymousUserId: String? = null
): InitializingBean {
    // If aspects are applied to the class using CGLIB proxy, no-argument constructor is required
    constructor() : this(
        anonymousUserId = null
    )

    override fun afterPropertiesSet() {
        instance = this
    }

    companion object {
        private lateinit var instance: HeaderHolder
        fun get(): HeaderHolder {
            return instance
        }
    }
}

在本课程中,我初始化

anonymousUserId
字段为
HeaderHolder

class HeaderInterceptor(
    private val headerHolder: HeaderHolder
) : HandlerInterceptor {
    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        val anonymousUserId = request.getHeader(ANONYMOUS_USER_ID_HEADER_NAME)
        headerHolder.anonymousUserId = anonymousUserId
        return true
    }

    companion object {
        const val ANONYMOUS_USER_ID_HEADER_NAME = "anonymous_user_id"
    }
}
spring kotlin dependency-injection
1个回答
0
投票

是的,可以通过静态方法访问Spring Beans。

但是你的代码很复杂;目前尚不清楚您要做什么以及在哪里看到空值。 您是故意使用请求范围吗?

根据很少的信息,我猜当您第一次访问该类时,它刚刚被实例化。 我建议您添加日志记录语句以了解何时调用(如果有的话)诸如

HeaderHolder
构造函数、
HeaderHolder.afterPropertiesSet()
HeaderInterceptor.preHandle()
等方法

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.