Override a spring scope in a child bean

2019-09-14 05:25发布

问题:

I have defined a spring bean extending another bean defined as singleton. Which means this:

<bean id="aChildBean" parent="aParentBean">
   <!-- ......->
</bean>

Now, I wonder if I could define the scope "request" in this bean. I know that the child bean inherits the scope of the parent, but I'm not sure that this could logically work. When I tested this, Spring spring generated the exception below:

Error creating bean with name 'aChildBean': Scope 'request' is not active for the
 current thread; consider defining a scoped proxy for this bean if you intend to refer
to it from a singleton; nested exception is java.lang.IllegalStateException: No thread
bound request found: Are you referring to request attributes outside of an actual web
request, or processing a request outside of the originally receiving thread? ...

So, I wonder if I could do such action. And, if the definition of a scoped bean solve the problem ?

Thanks in advance for your answers..

回答1:

Quote from documentation:

A child bean definition inherits constructor argument values, property values, and method overrides from the parent, with the option to add new values. Any initialization method, destroy method, and/or static factory method settings that you specify will override the corresponding parent settings.

The remaining settings are always taken from the child definition: depends on, autowire mode, dependency check, singleton, scope, lazy init.

So, your bean IS "request" scoped, but a "request" scope only makes sense in a web environment. See here the documentation of "request" scope.