In Scala, can I use Guice to inject Scala object
s?
For example, can I inject into s
in the following object?
object GuiceSpec { @Inject val s: String = null def get() = s }
Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.
@Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values. The Injector fulfills injection requests for: Every instance it constructs.
Some research on Google revealed that you can accomplish this as follows (the code that follows is a ScalaTest unit test):
import org.junit.runner.RunWith import org.scalatest.WordSpec import org.scalatest.matchers.MustMatchers import org.scalatest.junit.JUnitRunner import com.google.inject.Inject import com.google.inject.Module import com.google.inject.Binder import com.google.inject.Guice import uk.me.lings.scalaguice.ScalaModule @RunWith(classOf[JUnitRunner]) class GuiceSpec extends WordSpec with MustMatchers { "Guice" must { "inject into Scala objects" in { val injector = Guice.createInjector(new ScalaModule() { def configure() { bind[String].toInstance("foo") bind[GuiceSpec.type].toInstance(GuiceSpec) } }) injector.getInstance(classOf[String]) must equal("foo") GuiceSpec.get must equal("foo") } } } object GuiceSpec { @Inject var s: String = null def get() = s }
This assumes you are using scala-guice and ScalaTest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With