Created
April 8, 2017 18:06
-
-
Save agrajm/71c82f15b90058165a3e8c71aa07401c to your computer and use it in GitHub Desktop.
Using Google Guice in Scala - http://michaelpnash.github.io/guice-up-your-scala/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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