Search code examples
javadependency-injectionguice

How to inject my service class in my controller using guice?


I want to add DI features to an old codebase that uses simple instanciation of services in the controller layer.

I tried using @Inject before my serviceInterface field in my controller class. And annotate my ServiceInterface with @ImplementedBy(ServiceInterfaceImpl).

My code looks like below: Controller class

public class MyController {
    @Inject
    ServiceInterface serviceInterface;

    InitContext(..){
        // somecode
        Toto toto = serviceInterface.getToto(); //I get an NPE here
        // other code
    }
}

ServiceInterface Code:

@ImplementedBy(ServiceInterfaceImpl.class)
public interface ServiceInterface {
     Toto getToto();
}

ServiceInterfaceImpl Code:

@Singleton
public class ServiceInterfaceImpl implements ConventionServices {
     Toto getToto(){
          //somecode
     }
}

I expect that my service will be instanciated, but I get a NPE that indicate that I missed something, I tried adding @Provides before my service constructor but nothing changed.


Solution

  • You should inject ServiceInterface in your constructor, not as a field injection

    Your issue is that you have null values because field injection occurs after constructor injection. So move your injection to the constructor instead of the field injection:

    public class MyController {
      private final ServiceInterface serviceInterface;
      @Inject MyController(ServiceInterface serviceInterface) {
        this.serviceInterface = serviceInterface;
        Toto toto = serviceInterface.getToto();
      }
      ...
    }