I have such configuration where I defined headerHolder
bean. But now it is impossible to use it in static methods, because in this case I always have anonymousUserId
field equals null
. But at the same time, when using autowiring, it is filled with value. Why does it work so? How can I fix it?
@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
}
}
}
In this class I initialize anonymousUserId
field for 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"
}
}