Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring prototype beans in combination with singleton beans and dependency injection. Is there an approach that is configuration only?

Tags:

I have a singleton bean which needs for each call of a function to return a reference to a different (new) prototype bean. The only way that I can think of doing this is to programmatically retrieve a new prototype bean instance from the BeanFactory/ApplicatioContext by invoking its getBean() method. Code sample will follow...

Is there a better way to do this? Only via configuration, hopefully? (Personally, I doubt there is...)

<bean id="protoBean" scope="prototype"         class="com.blahblah.ProtoBean" />  <bean id="singletonBean"         class="com.blahblah.SingletonBean" />  public class ProtoBean {      .... }  public class SingletonBean {      private BeanFactory factory;      public ProtoBean dispense() {         return (ProtoBean) factory.getBean("protoBean");     }      .... } 
like image 534
Yaneeve Avatar asked May 06 '09 13:05

Yaneeve


People also ask

What happens if prototype bean is dependency injected into singleton during instantiation?

Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

What if prototype bean is injected to singleton Bean?

Let us look at a simple example when a prototype bean injected inside a singleton bean. Individually when a prototype bean used, every time a new instance is expected and for singleton the same instance. Singleton Bean always returns the same bean instance no matter where ever it is being referred.

Which one is the default scope of the beans prototype session request singleton?

Singleton Scope: By default, the scope of a bean is a singleton. Let's understand this scope with an example.


2 Answers

take a look at Method Injection

like image 173
dfa Avatar answered Oct 08 '22 05:10

dfa


From Spring 3.0, we can use <aop:scoped-proxy> for dependency injection of the proper scope. Behind the scene, Spring injects proxied objects and is responsible for finding the right scope context, may it be prototype, session or request etc. See the official documentations here.

And to make life easier, Spring has also introduced proxyMode attribute for @Scope, so we are not limited to XML declarations only. For example:

@Scope(value = "prototype", proxyMode = ScopedProxyMode.INTERFACES) 

Make sure to document clearly the injected bean is a proxy to warn others that getClass() and casting may not yield the expected result. Also, make sure equals() and hashCode() in the proxied class use access methods rather than directly accessing class variables.

like image 40
Christopher Yang Avatar answered Oct 08 '22 04:10

Christopher Yang