Does Spring's @RequestScope automatically handle proxying when injected in singleton beans?
Asked Answered
H

2

8

I'm using a Java8/Spring Boot 2 application. I want to inject a request-scoped bean into a singleton bean. The official documentation highlights that either a proxy or ObjectFactory/Provider should be used to ensure always getting the correctly scoped bean at runtime in the singleton bean. However, the @RequestScope annotation seems to "automatically" set some kind of proxy, as explained in the answer to this question.

I'm now wondering if the following three implementations are in fact identical and which one is preferred?

Approach 1: explicitly using objectFactory<>

@Component
@RequestScope
public class MyRequestScopedBean{...}

@Component
public class MySingletonBean{
    @Autowired
    private ObjectFactory<MyRequestScopedBean> myRequestScopedBean
}

Approach 2: inject normally, assuming the request scoped bean is proxied automatically?

@Component
@RequestScope
public class MyRequestScopedBean{...}

@Component
public class MySingletonBean{
    @Autowired
    private MyRequestScopedBean myRequestScopedBean
}

Approach 3: using @Configuration and @Bean because I don't know the difference and I'm worried they behave differently.

@Comfiguration
public class myBeanConfig{
   @Bean
   @RequestScope
   public MyRequestScopedBean getRequestScopedBean(){return new MyRequestScopedBean();}

}

@Component
public class MySingletonBean{
    @Autowired
    private MyRequestScopedBean myRequestScopedBean
}

I would prefer approach 2, because it is concise and handles the scoping/proxying automatically.

Would the answer change if my @Autowired bean is declared as a final field? I'm worried making it final somehow prevents the proxy from fetching the correctly fetching the new bean every request.

Had answered 20/5, 2019 at 8:48 Comment(0)
R
7

I have been using the 2nd approach in my projects and I have zero issues so far. The documentation does not mention it's a MUST to use ObjectFactory too. Don't think too much. If you run into any problems, you will see the error very clearly in the console. There's no reason to be afraid until you have an actual issue to deal with.

Revolting answered 20/5, 2019 at 9:47 Comment(0)
B
3

Yes, with @RequestScope the proxy is already default activated, the effect exactly equal to @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyModel = ScopedProxyMode.TARGET_CLASS)

Babblement answered 28/3, 2022 at 5:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.