1

if we have

1- a case scenario where we have class A configured as singleton and a child class B as a member within Class A configured as prototype.

2- Another case scenario, which is the opposite to the first one, where we have Class A defined as prototype and Class B defined as singleton.

How Spring container is gonna initialize and deal with these two situations when request is made to these classes A and B?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

1

Please take a look at this answer - Spring session-scoped beans as dependencies in prototype beans?

You can always inject a bean of wider scope (e.g. a singleton) into a bean of narrower scope (e.g. a session-scoped bean), but to it the other way around, you need a scoped-proxy.

This applies to your questions.

  1. You are injecting narrower scope bean in wider scoped bean. (Prototype is narrower than singleton). It should work for you.

  2. You are trying to inject wider scope bean into narrower scoped bean. You need to use a scoped-proxy.

Community
  • 1
  • 1
asg
  • 2,248
  • 3
  • 18
  • 26
  • I really appreciate your answer. But the question here is... How spring is gonna deal with these such requests for both scenarios when a request made for Class A or Class B? @asg – Omar AlQuaseer Apr 23 '16 at 20:44
  • @OmarAlQuaseer Apologies for late answer. Your case 1 is straight forward i.e. injecting prototype inside singleton. Prototype is a narrower scope bean (i.e. short lifespan bean) as compared to singleton (which is a longer lifespan bean). Hence, you should be okay. – asg Apr 24 '16 at 03:48
  • Only tricky case is the second one where you are trying to inject singleton inside prototype bean.. (i.e. longer life-span bean inside shorter life-span bean). So for this case spring recommends to use scoped-proxies (of singleton bean) instead of direct dependencies. Let me try to put some code for you. – asg Apr 24 '16 at 03:51
  • Thank you so much for your reply. Can you please put some code to make it more clear?. – Omar AlQuaseer Apr 28 '16 at 20:22