Thursday, January 03, 2013

Spring vs Guice default scopes

Spring and Guice are popular Inversion Of Control (IoC) frameworks. One of the most important aspects of IoC is how the framework creates new instances for value. This is the Scope. Some of the scopes are-

  1. Singleton (Spring default) - A single instance is created by the IoC container for the entire application lifetime.
  2. Prototype (Guice default) - A new instance is created whenever a value is needed.
In addition there are other scopes valid in a web context and custom scopes can also be defined. For additional details on scopes see Spring docs.

For stateless objects the programmer can choose either Singleton or Prototype. Guice docs recommend that prototype scope be used for Stateless objects even though only a single instance should suffice really. The rationale is to optimize for speed instead since singleton scopes require synchronization for implementation and today's JVMs are good at garbage collection.