Skip to content

Instantly share code, notes, and snippets.

@agrajm
Created April 8, 2017 18:06
Show Gist options
  • Save agrajm/f79f8c545aa988086ddd7ec7619131ae to your computer and use it in GitHub Desktop.
Save agrajm/f79f8c545aa988086ddd7ec7619131ae to your computer and use it in GitHub Desktop.
trait AService {
def service: String
}
class SomeService extends AService {
def service(): String = "someService"
}
class MyComponent @Inject()(val service: AService) {
def callTheService(): String = service.service
}
class SomeOtherService extends AService {
def service(): String = "someOtherService"
}
class DependencyInjectionTests extends FunSuite{
test("Basic Test") {
class ScalaModule extends AbstractModule {
@Override
protected def configure() {
bind(classOf[AService]).to(classOf[SomeService])
}
}
class ScalaModule2 extends AbstractModule {
@Override
protected def configure() {
bind(classOf[AService]).to(classOf[SomeOtherService])
}
}
val injector = Guice.createInjector(new ScalaModule)
val component = injector.getInstance(classOf[MyComponent])
assert("someService" === component.callTheService)
val injector2 = Guice.createInjector(new ScalaModule2)
val component2 = injector2.getInstance(classOf[MyComponent])
assert("someOtherService" === component2.callTheService)
}
test("single instance of service") {
// if you want to bind to a specific instance of a class...
class InstanceExampleModule extends AbstractModule {
@Override
protected def configure() {
val instance1 = new InstanceService("instance1")
bind(classOf[AService]).toInstance(instance1)
}
}
val injector = Guice.createInjector(new InstanceExampleModule)
val service = injector.getInstance(classOf[AService])
assert("instance1" === service.service)
}
class InstanceService(val value: String) extends AService {
def service(): String = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment