Reputation: 41
I think this is a trivial problem, yet I couldn't find any discussions about it.
I have DeeplyNestedObject
whose object graph should be autowired through the injection of Dependency
. Inside this object graph Dependency
should be singleton scoped.
class DeeplyNestedObject {
Dependency dependency;//should be same instance as in SomeOtherObject
SomeOtherObject someOtherObject;
@Autowired
public DeeplyNestedObject(Dependency dependency,
SomeOtherObject someOtherObject){
this.dependency = dependency;
this.someOtherObject = someOtherObject;
}
}
//this is just some other class nested inside DeeplyNestedObject's object graph
class SomeOtherObject{
Dependency dependency;//should be same instance as in DeeplyNestedObject
@Autowired
public DeeplyNestedObject(Dependency dependency){
this.dependency = dependency;
}
}
Since I only need Dependency
to autowire SomeOtherObject and thus DeeplyNestedObject, this bean configuration should be sufficient:
@Bean
Dependency dependency(){
return new Dependency();
}
I have three requirements though
DeeplyNestedObject
shall be prototyped, so I want a new instance of this object graph every time I autowire it somewhereDependency
should be treated as a singleton within this object graph, I can't solve the following problem:
Dependency
in DeeplyNestedObject and SomeOtherObject would be different)DeeplyNestedObject
and its object graphs would share the same Dependency
object)
Basically what I think I need is to introduce another IoC container for DeeplyNestedObject into which I can inject Dependency and then provide it as a Singleton for the DeeplyNestedObject
graph. However, I didn't see any solution like this so far.
Upvotes: 1
Views: 88
Reputation: 131346
If I scope Dependency as prototype, I will always get a new instance, breaching constraint 2
I don't think.
Spring creates a new instance for a prototype scoped bean only as an injection or a bean loading is requested.
So if you don't perform other bean loading/injection of Dependency
in DeeplyNestedObject
once the DeeplyNestedObject
bean was added in the bean container, you would have a distinct Dependency
instance by DeeplyNestedObject
instance.
Upvotes: 2