|
Guice20
Guice 2.0 Release
Guice 2.0Released May 19, 2009 Downloads
DocsNew FeaturesSmall Features
Provider MethodsCreating 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 OverridesOverride the bindings from one module with another: Module functionalTestModule
= Modules.override(new ProductionModule()).with(new OverridesModule());Multibindings, MapBindingsBind 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 ModulesPrivateModules can be used to create bindings that are not externally visible. This makes it easier to encapsulate dependencies and to avoid bind conflicts. ServletsServletModule 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 InjectorsInjector.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 ReportingExceptions 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 APILike 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 InjectionsType and instance listeners enable Guice to host other frameworks that have their own injection semantics or annotations. Pluggable Type ConvertersConstant String bindings can be converted to arbitrary types (such as dates, URLs, or colours) using pluggable type converters. Available without AOPGuice 2.0 is available without AOP for platforms like Android that don't support bytecode manipulation. OSGi-friendly AOPGuice 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 ResolutionParameterized 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.0Guice 2.0 breaks compatibility with Guice 1.0 as described below. See the JDiff change report for complete details. Exception TypesIn 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 TypesGuice 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 ClassesGuice 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() {...}
}
}KeysGuice 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 ImplementationsGuice 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.getBindingGuice 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 ChangesSourceProviders 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. |
Sign in to add a comment
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!