Skip to content
Pedro Felix edited this page Feb 9, 2011 · 11 revisions

The Guice container

Concepts

Conceitos do Guice

A code example

IntroTest

Injectors and Guice

  • Instances provided by injectors
public interface Injector{
	<T> T getInstance(Class<T> type)
	...
}
  • Injectors created by the Guice static class
public final class Guice{
	static Injector createInjector(Module...)
}

Modules and bindings

  • Injector creation is configured by modules

  • A Module instance

    • is a binding collection
    • defined using a fluent interface
  • Example

bind(Service.class).to(ServiceImpl.class);
bind(Integer.class).annotatedWith(Names.named(“timeout”))
	.toInstance(10);
  • A Binding
    • maps types to their implementations
    • is polymorphic: linked bindings, instance bindings

Bindings

  • Linked bindings

    • Allows for chaining
  • Instance bindings

  • Binding annotations

  • Provider bindings

  • @Provides annotated method bindings

  • Built-in bindings

    • Loggers
    • The injector
  • Just-In-Time bindings

Scopes

  • Scopes define the instance lifetime

    • Per injection
    • Per application (singleton)
    • Per session
    • Per request
  • Example

Injections

  • Constructor injection

    • Public no-arguments constructor
    • Constructor annotated with @Inject
  • Method/setter injection

    • Annotated with @Inject
    • Allows for @Inject(optional=true)
  • Field injection

  • On demand field injection

  • Example

anInjector.injectMembers(aPreviouslyCreatedInstance);
  • Providing injection
    • Used for lazy or multiple instantiation
interface Provider<T>{
	T get();
}

ctor(Service1 svc, ...){
	// use svc instance
}
ctor(Provider<Service1> prov, ...){
	// use prov to create as many instances as necessary,
	// when necessary
}