Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Guice inject Scala objects

Tags:

In Scala, can I use Guice to inject Scala objects?

For example, can I inject into s in the following object?

object GuiceSpec {   @Inject   val s: String = null    def get() = s } 
like image 326
Hbf Avatar asked Dec 09 '12 21:12

Hbf


People also ask

What does @inject do Guice?

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.

What is @inject annotation in Guice?

@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.


1 Answers

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.

like image 63
Hbf Avatar answered Oct 02 '22 13:10

Hbf