Skip to content

Using Dependency Injection

Eric Lam edited this page Jun 13, 2022 · 1 revision

How to use the dependency injection

using dependency injection is simple, declare a field and annotate it with @Inject

(Spigot for example)

public class TesterLifeCycle implements ELDLifeCycle {

    @Inject
    private TesterSingleton singleton;

    @Inject
    private TestConfig config;

    @Override
    public void onEnable(JavaPlugin javaPlugin) {
        singleton.setKey("abc", "xyz");
        singleton.setKey("xyz", "abc");
        javaPlugin.getLogger().info(singleton.getString());
        javaPlugin.getLogger().info(config.toString());
    }

    @Override
    public void onDisable(JavaPlugin javaPlugin) {
        javaPlugin.getLogger().info(singleton.getString());
        javaPlugin.getLogger().info(config.toString());
    }
}

you can also inject with constructor:

public class TestManager {

    private final TesterSingleton singleton;
    
    @Inject
    public TestManager(TesterSingleton singleton){
        this.singleton = singleton;
        singleton.setKey("start", "started a insertion in constructor");
    }

    public void doSomething(){
        System.out.println(singleton.getString())
    }
   
}

What can I inject?

  • Configuration
  • Service
  • Singleton
  • Plugin

Where I can use @Inject?

  • Command (which implements CommandNode)
  • Listener
  • Registered Singleton
  • Registered Services
  • LifeCycle (which implements LifeCycle)