Hi,

I am using springboot 2.7.14 and running Java 17.

I have created this class

class RequestContextHolder {
    private var headers: Map<String, String?>? = null

    fun setHeaders(headers: Map<String, String?>) {
        this.headers = headers
    }

    fun getHeaders(): Map<String, String?>? {
        return this.headers
    }
}

Declared it as a request scoped bean here

    @Bean
    @RequestScope
    fun requestContextHolder(): RequestContextHolder {
        return RequestContextHolder()
    }

Used the bean as a dependency in my web filter as follows


@Component
class AppRequestContextFilter(
    private val requestContextHolder: RequestContextHolder
) : OncePerRequestFilter() {
---
}

But as opposed to my expectation, the instance of requestContextHolder being returned seems to retain the values from the previous requests.

This issue goes away if I instead do the following and make the RequestContextHolder class a Spring component

@Component
@RequestScope
class RequestContextHolder {
    private var headers: Map<String, String?>? = null

    fun setHeaders(headers: Map<String, String?>) {
        this.headers = headers
    }

    fun getHeaders(): Map<String, String?>? {
        return this.headers
    }
}

Is this inconsistency between @Component and @Bean expected? If so, I do not see it documented anywhere. Please clarify.

Comment From: philwebb

Spring Boot 2.7 is out of OSS support so you should consider upgrading.

The @RequestScope annotation is part of Spring Framework, I'm not sure if it working differently when used on a class vs a bean method is by design or not. I would suggest asking for clarification at https://github.com/spring-projects/spring-framework/issues/.

My best guess would be you're getting a scoped proxy when using it on the class but not when using it on a @Bean method. You could try setting the proxyMode attribute on the annotation. Another option would be to inject an ObjectProvider<RequestContextHolder> into your filter so you can always request a fresh bean.

Comment From: mgunasekha-chwy

Thanks for your quick response Phil. I will try out your suggestions as well as reach out to the spring team for further clarification.