简体   繁体   中英

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.

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();
  }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM