Reputation: 36686
I have the following code to define a bean request scoped bean inside my Spring application.
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBean() {
return new MyBean(); // actually it is a more complex initialization
}
But sometimes I will want to use the same bean in a offline application where request
scope is not available, only singleton
and prototype
are.
Is there a way to make this same bean assume a singleton
form when request
is not available?
Upvotes: 1
Views: 575
Reputation: 1823
can you rely on a spring profile ?
You could maybe extract the bean creation in a private method used by 2 @Bean
with different @Scope
and @Profile
Something like this :
@Bean
@Profile('prod')
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBeanProd() {
return getMyBean()
}
@Bean
@Profile('test')
@Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBeanWithoutRequestScope() {
return getMyBean()
}
privateMyBean getMyBean() {
return new MyBean(); // actually it is a more complex initialization
}
Upvotes: 1