muley
muley

Reputation: 41

Spring: How to treat prototyped beans in a spring container, singleton scoped for a certain subpart of the object graph?

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

  1. The DeeplyNestedObject shall be prototyped, so I want a new instance of this object graph every time I autowire it somewhere
  2. A Dependency should be treated as a singleton within this object graph,
  3. Each DeeplyNestedObject should have its own instance of Dependency

I can't solve the following problem:

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

Answers (1)

davidxxx
davidxxx

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

Related Questions