Skip to content

AutoBindSingleton

Jordan Zimmerman edited this page May 30, 2013 · 5 revisions

Description

Classes annotated with AutoBindSingleton will get auto-bound as Eager Singletons. This is useful for stand-alone classes such as cleanup tasks, etc. that aren’t referred to in the code. E.g.

@AutoBindSingleton
public class MyClass {
   ...
}

If MyClass is in a package specified via usingBasePackages(), Governator will automatically bind it as:

binder.bind(MyClass.class).asEagerSingleton();

By default, @AutoBindSingleton binds to the class that has the annotation. You can
also set the value to any base class/interface that you want to bind to. For example:

@AutoBindSingleton(BaseClass.class)
public class MyClass implements BaseClass {
   ...
}

If MyClass is in a package specified via usingBasePackages(), Governator will automatically bind it as:

binder.bind(BaseClass.class).to(MyClass.class).asEagerSingleton();

You can specify generic base classes/interfaces by listing the raw type of the class. E.g.

@AutoBindSingleton(BaseClass.class)
public class MyClass extends BaseClass<String> {
   ...
}

Multibinding

AutoBindSingleton can be used to do multibinding by setting multiple=true. You must also specify a base class. Example:

public interface MyFace { ... }

@AutoBindSingleton(multiple=true, baseClass=MyFace.class)
public class ClassOne implements MyFace { ... }

@AutoBindSingleton(multiple=true, baseClass=MyFace.class)
public class ClassTwo implements MyFace { ... }

@Singleton
public class MyContainer {
    @Inject
    public MyContainer(Set<MyFace> objs) { ... }
}

Supported Types

AutoBindSingleton supports the following types of classes:

  • General purpose singletons
  • Guice Providers
  • Guice Modules