Skip to content

nbauernfeind/scala-guice

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Scala extensions for Google Guice 4.0

Master: Build Status Develop: Build Status

Please submit pull requests against the develop branch.

Note: Multibinding behaviour had changed in beta4, duplicates are now ignored instead of throwing an exception.

Getting Started

Add dependency

We currently support Scala 2.10, 2.11

maven:
<dependency>
    <groupId>net.codingwell</groupId>
    <artifactId>scala-guice_2.10</artifactId>
    <version>4.0.0-beta4</version>
</dependency>

#####sbt:

"net.codingwell" %% "scala-guice" % "4.0.0-beta4"
gradle:
'net.codingwell:scala-guice_2.10:4.0.0-beta4'

Mixin

Mixin ScalaModule with your AbstractModule for rich scala magic (or ScalaPrivateModule with your PrivateModule):

class MyModule extends AbstractModule with ScalaModule {
  def configure {
    bind[Service].to[ServiceImpl].in[Singleton]
    bind[CreditCardPaymentService]
    bind[Bar[Foo]].to[FooBarImpl]
    bind[PaymentService].to[CreditCardPaymentService]
  }
}

class MyPrivateModule extends PrivateModule with ScalaPrivateModule {
  def configure {
    bind[Foo].to[RealFoo]
    expose[Foo]

    install(new TransactionalBarModule())
    expose[Bar].annotatedWith[Transactional]

    bind[SomeImplementationDetail]
    install(new MoreImplementationDetailsModule())
  }
}

Inject

Wrap the injector in a ScalaInjector for even more rich scala magic:

object MyServer {
  def main(args: Array[String]) {
    val injector = Guice.createInjector(new MyModule(), new MyPrivateModule)

    import net.codingwell.scalaguice.InjectorExtensions._
    val service = injector.instance[Service]
    val foo = injector.instance[Foo]
    ...
  }
}

Additional Features

Module Traits

class MyModule extends AbstractModule with ScalaModule
class MyPrivateModule extends PrivateModule with ScalaPrivateModule

This gives to access to scala style bindings:

bind[A].to[B]
bind[A].to(classOf[B])
bind[A].to(typeLiteral[B])
bind[A].toInstance("A")
bind[A].annotatedWith[Ann].to[B]
bind[A].annotatedWith( Names.named("name") ).to[B]
bind[A].annotatedWithName("name").to[B]
bind[A].toProvider[BProvider]
bind[A].toProvider[TypeProvider[B]]
bind[A[String]].to[B[String]]
bind[A].to[B].in[Singleton]

Multibinding

The ScalaMultibinder adds scala style multibindings:

val multi = ScalaMultibinder.newSetBinder[String]( binder )
multi.addBinding.to[A]
multi.addBinding.toInstance("A")

And the stuff we forgot...

If you find a feature we support but don't mention here, submit an issue and we will add it.

If you find a feature we don't support but want, implement it and send us a pull request. Alternatively, you can file an issue and we may or may not get to it.

About

Scala extensions for Google Guice

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Scala 100.0%