Skip to content

AutoBind

Eduards Sizovs edited this page Jul 9, 2014 · 3 revisions

Governator has a method for auto binding injected constructor/method arguments and injected fields via the AutoBind annotation. As Governator is scanning the CLASSPATH, it looks for injection sites that are annotated with AutoBind (or custom auto bind annotations – see below). The actual binding is done via an AutoBindProvider that you create.

Here’s an example usage: imagine a class “PropertyName” that is used throughout your application. PropertyName is a POJO that holds a String – a property name. Everywhere PropertyName is used it might have a different value and there are possibly hundreds of these usages. Without Governator, you’d need to bind each of those usages. With @AutoBind, you can create the bindings much easier.

public class MyClass {
    @Inject
    public MyClass(@AutoBind("a value") PropertyName p)
}

public class AnotherClass {
    @Inject
    public AnotherClass(@AutoBind("different value") PropertyName p)
}

...

To do the actual binding, create an instance of AutoBindProvider. For the above example, it would be something like this:

public class MyAutoBindProvider implements AutoBindProvider<AutoBind> {
    public void     configure(Binder binder, AutoBind annotation) {
        PropertyName p = new PropertyName(annotation.value());
        binder.bind(PropertyName.class).annotatedWith(AutoBinds.withValue(annotation.value())).toInstance(p);
    }
}

You must bind your AutoBindProvider in Governator’s Bootstrapping phase:

LifecycleInjectorBuilder    builder = ...
builder.withBootstrapModule(new BootstrapModule(){
    public void configure(BootstrapBinder binder) {
        TypeLiteral<AutoBindProvider<AutoBind>> typeLiteral = new TypeLiteral<AutoBindProvider<AutoBind>>(){};
        binder.bind(typeLiteral).toInstance(MyAutoBindProvider);
    }
});

Custom AutoBind Annotations

AutoBind supports custom annotations as well. You can use custom AutoBind annotations to capture additional parameters and/or to differentiate different auto bind scenarios. A custom AutoBind annotation looks like this:

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@BindingAnnotation
@AutoBind
public @interface CustomAutoBind
{
    // add whatever parameters you need

    String      name();

    long        id();
}

Notice that your custom Auto Bind annotation must itself be annotated with @AutoBind and @BindingAnnotation. You then must bind an AutoBindProvider for the custom annotation in the bootstrap binder:

binder.bind(new TypeLiteral<AutoBindProvider<CustomAutoBind>>(){}).toInstance(MyCustomAutoBindProvider);