Monday, March 24, 2014

The fundamental difference between Guice and Spring

If you do a Google search for the difference between Guice and Spring chances are you will find many, many pages arguing about XML configuration, performance and the relative weight of the packages. However, in my experience most developers fail to realise the core difference between Guice and Spring.

Guice and Spring represent fundamentally different dependency injection paradigms.

In Spring:
  • There is an application context that holds instantiated objects that may be injected into their collaborators.
  • The default scope is singleton, but the context may hold proxies or factories for some objects that require different scopes.
  • If an object in the context requires an instance of a type to be injected that does not exist in the context, an exception will be thrown.
In Guice:
  • There is an injector that can create instances of any type requested.
  • The default scope is to create a new instance for every injection.
  • If an object requires an instance of any type, it will be instantiated by default.
These differences are pretty significant, but I think they are lost on a lot of developers. It's fairly common to see huge module files where everything is a singleton, and if that is the way your application is best structured, perhaps you should be using Spring instead.

No comments: