Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with both @Bozho and @stivio answers.</p> <p>The preferred options are to either pass store no state in a singleton scoped beans, and pass in a context object to the methods, or to use a prototype / request scoped beans that get created for every processing cycle. Synchronization can be usually avoided, by choosing one of these approaches, and you gain much more performance, while avoiding deadlocks. Just make sure you're not modifying any shared state, like static members.</p> <p>There are pros and cons for each approach:</p> <ol> <li>Singlton beans are act as a service-like class, which some may say are not a good Object-Oriented design.</li> <li>Passing context to methods in a long chain of methods may make your code messy, if you're not careful.</li> <li>Prototype beans may hold a lot of memory for longer than you intended, and may cause memory exhaustion. You need to be careful with the life cycle of these beans.</li> <li>Prototype beans may make your design neater. Make sure you're not reusing beans by multiple threads though.</li> </ol> <p>I tend to go with the service approach in most simple cases. You can also let these singleton beans create a processing object that can hold it's state for the computation. This is a solution that may serve you best for the more complexed scenarios.</p> <p><strong>Edit:</strong> There are cases when you have a singleton bean depending on prototype scoped bean, and you want a new instance of the prototype bean for each method invocation. Spring supplies several solutions for that:</p> <p>The first is using <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-sing-prot-interaction" rel="noreferrer">Method Injection</a>, as described in the Spring reference documentation. I don't really like this approach, as it forces your class to be abstract.</p> <p>The second is to use a <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.html" rel="noreferrer">ServiceLocatorFactoryBean</a>, or your own factory class (which needs to be injected with the dependencies, and invoke a constructor). This approach works really well in most cases, and does not couple you to Spring.</p> <p>There are cases when you also want the prototype beans to have runtime dependencies. A good friend of mine wrote a good post about this here: <a href="http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/" rel="noreferrer">http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload