javaguice

Google Guice provider not creating instance of dependency


I am new to Google Guice and trying to figure out how it works. I have the following code where I created a module that provides implementations of the injected dependencies:

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provides;

public class GuiceTest {

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new TestModule());
        TestClass testClass = injector.getInstance(TestClass.class);
        testClass.test();
    }

}

class TestClass {

    @Inject
    SomeClass someClass;

    public void test() {
        someClass.test();
    }

}

class SomeClass {

    @Inject
    SomeDependency someDependency;

    public void test() {
        someDependency.test();
    }

}

class SomeDependency {

    public void test() {
        System.out.println("SomeDependency test");
    }

}

class TestModule extends AbstractModule {

    @Override
    protected void configure() {}

    @Provides
    public SomeClass provideSomeClass() {
        return new SomeClass();
    }

    @Provides
    public SomeDependency provideSomeDependency() {
        return new SomeDependency();
    }

}

SomeClass gets injected all good but SomeDependency is null in the SomeClass class. I am not sure why it would be null as I did define a provider in the module. What is the reason the SomeDependency instance would be null?


Solution

  • As pointed out by Andy Turner, you are not asking Guice to create your instance of SomeClass but you are explicitly instantiating it in the method annotated with @Provides. If you remove that, Guice should be able to create your instance of SomeClass by invoking its no-arg constructor.