Search code examples
scalaguice

Guice Scala DI, understanding how


Will default constructor be called in scala if I have @Provides annotation in my Module file to return an object but I never inject it anywhere?


Solution

  • According to official Google Guice documentation: https://github.com/google/guice/wiki/ProvidesMethods

    @Provides Methods When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method's return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.

    So, the constructor will never have been invoked.

    If you need to construct the object anyway, use com.google.inject.Singleton annotation:

    import com.google.inject._
    
    class DbModule extends AbstractModule {
    
      @Provides
      @Singleton
      def helloWorld: HelloWorld = new HelloWorld();
    
    }
    
    class HelloWorld() {
      println("Hello world!")
    }
    

    will print:

    Hello world!