Search code examples
scalaguice

Scala Guice pass parameter


I have the following Guice binding:

val profile = "dev";
bind[DbClient].annotatedWith(Names.named("postgres")).to[PostgresClient].in[Singleton]

I'd like to pass profile as a parameter to PostgresClient instance. Please advice how it can be achieved with Guice and Scala.


Solution

  • You can work with @Provides (described here: https://github.com/google/guice/wiki/ProvidesMethods)

    And construct your DbClient manually

      @Provides
      @Singleton
      @Named("postgres")
      def provideDbClient(): DbClient = {
        new PostgresClient("dev")
      }
    

    I haven't tried @Singleton - but the rest we us frequently.