Skip to content

Circular references between custom scoped beans should be supported [SPR-2691] #7379

Closed
@spring-projects-issues

Description

@spring-projects-issues

Piotr Kolaczkowski opened SPR-2691 and commented

Hi. I created a custom scope by overriding the get method in such a way:

public Object get(String name, ObjectFactory factory) {
if (name was associated with the current thread)
return object associated with the current thread;
Object result = factory.getObject();
associate result with the current thread;
return result;
}

I registered scope programatically and it works as expected until I do a circular reference between two beans using this scope:

<bean name="bean1" class="foo.Foo" scope="myScope">
<property name="bean2" ref="bean2"/>
</bean>
<bean name="bean2" class="bar.Bar" scope="myScope">
<property name="bean1" ref="bean1"/>
</bean>

Spring falls into an endless loop creating bean1, bean2, bean1, bean2, ....
If I change any of scopes to "singleton", it creates each bean at most 2 times (or once if both scopes are singleton).

I think the problem is that while the factory.getObject() is called, the object is NOT YET registered within the given scope, so the next call to the Scope.get(...) from the referenced bean enters factory.getObject() once again, closing the loop. The next call should have returned the already created bean, but wait.... it cannot be returned because we haven't returned from the factory.getObject() yet... So it is the chicken and egg problem.

I suggest providing 2-step bean instantiation: 1st instantiate the bean using constructor injection, and in 2nd step complete the bean by launching the setter injection. Then it could be possible to
associate the object with the scope (e.g. current thread) between those steps.

By the way is there any reasonable work-around other than removing the circular reference?


Affects: 2.0 final

Issue Links:

1 votes, 1 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions