My favorites | Sign in
Google
                
Search
for
Updated May 30, 2009 by limpbizkit
Guice20  
Guice 2.0 Release

Guice 2.0

Released May 19, 2009

Downloads

Docs

New Features

Small Features

Provider Methods

Creating custom providers without all of the boilerplate. In any module, annotate a method with @Provides to define logic that will be used to provide that type:

class PaymentsModule extends AbstractModule {
  public void configure() {
    ...
  }

  @Provides @Singleton
  PaymentService providePaymentService(CustomerDb database) {
    DatabasePaymentService result = new DatabasePaymentService();
    result.setDatabase(database);
    result.setReplicationLevel(5);
    return result;
  }

Parameters to the @Provides method will be injected. It can optionally be annotated with a scoping annotation (like @Singleton). The method's returned type is the bound type. Annotate the method with a binding annotation (like @Named("replicated")) to create a binding for the annotated type.

Binding Overrides

Override the bindings from one module with another:

Module functionalTestModule 
        = Modules.override(new ProductionModule()).with(new OverridesModule());

Multibindings, MapBindings

Bind elements of Sets and Maps, then inject the full collection. Bindings are aggregated from all modules.

public class SnacksModule extends AbstractModule {
  protected void configure() {
    MapBinder<String, Snack> mapBinder
        = MapBinder.newMapBinder(binder(), String.class, Snack.class);
    mapBinder.addBinding("twix").toInstance(new Twix());
    mapBinder.addBinding("snickers").toProvider(SnickersProvider.class);
    mapBinder.addBinding("skittles").to(Skittles.class);
  }
}

Private Modules

PrivateModules can be used to create bindings that are not externally visible. This makes it easier to encapsulate dependencies and to avoid bind conflicts.

Servlets

ServletModule now supports programmatic configuration of servlets and filters (get rid of web.xml).

These servlets may be:

Guice Servlet also supports regex URL mapping and the ability to package and bundle your own servlet libraries (for example, an SOAP web service).

GuiceServletContextListener can be used to help bootstrap a Guice application in a servlet container.

Child Injectors

Injector.createChildInjector allows you to create child injectors that inherit the bindings, scopes, interceptors and converters of their parent. This API is primarily intended for extensions and tools.

Even Better Error Reporting

Exceptions in Guice 1.0 tend to include long chains of 'caused by' exceptions. We've tidied this up! Now a single exception describes concisely what Guice was doing when the problem occurred.

Introspection API

Like java.lang.reflect, but for Guice. It lets you rewrite a Module, tweaking bindings programatically. It also lets you inspect a created injector, and examine its bindings. This is intended to enable simpler, more powerful extensions and tools for Guice.

Custom Injections

Type and instance listeners enable Guice to host other frameworks that have their own injection semantics or annotations.

Pluggable Type Converters

Constant String bindings can be converted to arbitrary types (such as dates, URLs, or colours) using pluggable type converters.

Available without AOP

Guice 2.0 is available without AOP for platforms like Android that don't support bytecode manipulation.

OSGi-friendly AOP

Guice does bytecode generation internally to implement AOP. In version 2.0, generated classes are loaded by a bridge classloader that works in managed environments such as OSGi.

Type Resolution

Parameterized injection points allow you to inject types like Reducer<T> or Converter<A, B>. Guice will figure out what T is and find the binding for that type. TypeLiteral injection means you can inject a TypeLiteral<T> into your classes. Use this to reify Java 5 type erasure. The TypeLiteral class now includes library methods for manual type resolution.

Migrating from Guice 1.0

Guice 2.0 breaks compatibility with Guice 1.0 as described below. See the JDiff change report for complete details.

Exception Types

In Guice 1.0, when a custom provider throws an unchecked exception, sometimes Guice wraps the exception and sometimes it doesn't. This depends on whether the provider is being called directly (via Provider.get()) or indirectly (such as for injecting into another type).

In Guice 2.0, any time a provider or injection throws, Guice wraps it in a ProvisionException. This rule is simpler, and it makes it easier to write fault-tolerant code with Guice.

Injector creation problems are always reported as CreationException. Runtime configuration problems (ie. programmer errors) are always reported as ConfigurationException.

ProvisionException, ConfigurationException and OutOfScopeException are now public.

Abstract Types

Guice doesn't support injecting into abstract types. The messaging around this has been improved since 1.0, and some code that was silently failing now throws exceptions.

Inner Classes

Guice used to support constructor injection of nonstatic inner classes. So this used to work, but it won't anymore:

public class FooTest extends TestCase {
  public void testFoo() {
    Foo foo = Guice.createInjector().getInstance(FakeFoo.class)
  }

  class FakeFoo implements Foo {
    @Inject TestFoo() {...}
  }
}

Keys

Guice now canonicalizes primitive types (like int.class) and array types (like Integer[].class) when they're used in Keys. It now supports wildcards like List<?> in keys - use @Provides to bind these.

Annotation Implementations

Guice 2.0 fixes the treatment of equals() and hashCode() for fieldless annotations. Annotation implementations that don't implement equals() and hashCode() may have worked in 1.0 but will be broken in 2.0.

Injector.getBinding

Guice 2.0 throws an exception if the binding cannot be resolved. The old version used to return null. To get the old behaviour, use injector.getBindings().get(key).

SPI Changes

SourceProviders have been replaced with Binder.withSource and Binder.skipSources. These new methods are easier to call and test. They don't require static initialization or static dependencies.


Comment by padcom, Sep 22, 2009

I'd like to point out one another breaking change that's probably the most noticeable one if you're migrating code from 1.0 to 2.0. In 1.0 constructor injection used to work without specifying any annotations. So if one had classes that should receive dependencies but had no control over the code it'd still work if the proper dependencies were available during the creation of the injector.

This is a serious problem in 2.0 - can anyone give me some directions about how to make this work in the new version?

Thanks!


Sign in to add a comment