Skip to content

Injection

Harry Freeborough edited this page Dec 6, 2016 · 6 revisions

Injection

Modularity uses Guice in order to inject the modules with objects on creation. For example, by default Guice injects a java.util.logging.Logger. There are multiple ways to inject variables in Guice, in my opinion the two best ways are:

Annotating each variable you would like to inject with @Inject, for example:

import com.google.inject.Inject;
import com.harryfreeborough.modularity.Module;

import java.util.logging.Logger;

@Module(name = "Test", desc = "A test module", enabled = false)
public class TestModule {

    @Inject private Logger log;

}

And annotating your constructor with @Inject and taking in the variables you would like to be injected as parameters, for example:

import com.google.inject.Inject;
import com.harryfreeborough.modularity.Module;

import java.util.logging.Logger;

@Module(name = "Test", desc = "A test module", enabled = false)
public class TestModule {

    private final Logger log;

    @Inject
    public TestModule(Logger log) {
        this.log = log;
    }

}

Although, I would recommend the latter because: this allows verification of the variables which can not be done as easily with the first method due to the fact that the constructor is called before fields annotated with @Inject are set meaning that the @Inject fields will not be initialized when the constructor is called. Another reason that I would recommend the latter method is because this allows for easier testing due to the fact that the object can be built without injection.

By default it is also possible to inject other Modules and AutoRegisters.

BukkitGuiceModule

The BukkitGuiceModule adds the default injection of the following:

  1. Plugin -> Your plugin instance
  2. Server
  3. PluginManager
  4. File annotated with @DataDir -> Your plugin's data directory

This injector module also automatically registers your Modules and AutoRegisters as listeners if they implement Listener.

You can add the BukkitGuiceModule by adding it as an injector module to your ModuleLoader:

new ModuleLoader()
        .addInjectorModules(new BukkitGuiceModule(plugin))
        .load();