Annotation Type BindsInstance
-
@Documented @Retention(RUNTIME) @Target({METHOD,PARAMETER}) @Beta public @interface BindsInstanceMarks a method on a component builder or a parameter on a component factory as binding an instance to some key within the component.For example:
@Component.Builder interface Builder { @BindsInstance Builder foo(Foo foo); @BindsInstance Builder bar(@Blue Bar bar); ... } // or @Component.Factory interface Factory { MyComponent newMyComponent( @BindsInstance Foo foo, @BindsInstance @Blue Bar bar); }will allow clients of the builder or factory to pass their own instances of
FooandBar, and those instances can be injected within the component asFooor@Blue Bar, respectively. It's important to note that unlike in factories, the methods in builders should only accept and bind a single parameter each. Using the following will result in an error:@Component.Builder interface Builder { // Error! Builder methods can only have one parameter @BindsInstance Builder fooAndBar(Foo foo, @Blue Bar bar); ... }@BindsInstancearguments may not benullunless the parameter is annotated with@Nullable.For builders,
@BindsInstancemethods must be called before building the component, unless their parameter is marked@Nullable, in which case the component will act as though it was called with anullargument. Primitives, of course, may not be marked@Nullable.Binding an instance is equivalent to passing an instance to a module constructor and providing that instance, but is often more efficient. When possible, binding object instances should be preferred to using module instances.