Skip to content

Custom Injection

Harry Freeborough edited this page Dec 6, 2016 · 1 revision

Custom Injection

If you want to inject your own objects there are three options:

  • Let the injector create the object for you and share the object between each module. This can be done by simply annotating the class with @AutoRegister, if this class requires any objects, it must also use @Inject.
  • Let the injector create the object for you and have a seperate object for each module. This behaviour is automatically done to an object. Once again, if this class requires any object, it must use @Inject.
  • Binding each object yourself using injector modules, in order to do this, you must extend Guice's AbstractModule and implement the configure method, once you have done this you can bind the instances like such:
import com.google.inject.AbstractModule;

public class CustomInjectorModule extends AbstractModule {

    private final SpecialObject specialObject;

    public CustomInjectorModule(SpecialObject specialObject) {
        this.specialObject = specialObject;
    }

    @Override
    protected void configure() {
        this.bind(SpecialObject.class).toInstance(this.specialObject);
    }

}

This guice module must then be added as an InjectorModule with your ModuleLoader like such:

new ModuleLoader()
        .addInjectorModules(new CustomInjectorModule(specialObject))
        .load();

For more information on this, refer to the Guice wiki.