The use of the use of the SCALA Guice framework in the Java library
Scala Guice is a dependent injection framework used in SCALA, which is built based on Google Guice.This article will introduce how to use the Scala Guice framework in the Java library.
Use Scala Guice in the Java class library, you need to follow the following steps:
Step 1: Add dependencies
First, add scala guice to the project's configuration file (such as `Pom.xml` or Build.gradle).The following is an example of Maven:
<dependencies>
<dependency>
<groupId>net.codingwell</groupId>
<artifactId>scala-guice_2.13</artifactId>
<version>4.2.6</version>
</dependency>
</dependencies>
Step 2: Create the scala module
Next, you need to create a SCALA module to configure the binding relationship of injecting.In the Scala Guice, the module is defined by extending the `Scalamodule` class.The following is an example:
import com.google.inject.AbstractModule
import net.codingwell.scalaguice.{ScalaModule, ScalaMultibinder}
class MyModule extends AbstractModule with ScalaModule {
override def configure() = {
// Binded interface to implementation class
bind[MyService].to[MyServiceImpl]
// Bind multiple implementation classes to access to interfaces
val multibinder = ScalaMultibinder.newSetBinder[Plugin](binder)
multibinder.addBinding.to[PluginA]
multibinder.addBinding.to[PluginB]
}
}
Step 3: Start SCALA Guice
At the entrance of the project, Scala Guice needs to be started and loaded the created SCALA module.The following is an example:
import com.google.inject.Guice
import net.codingwell.scalaguice.InjectorExtensions.ScalaInjector
object Main {
def main(args: Array[String]): Unit = {
val injector = Guice.createInjector(new MyModule)
val myService = injector.instance[MyService]
// Use myService to operate
}
}
In the above examples, we obtain the binding instance through the `Instance" method of the `Scalainjector` extended class.
Summarize
This article introduces how to use the Scala Guice framework in the Java library.First of all, we added SCALA Guice dependence, then created a Scala module, and configured the binding relationship injection in this module.Finally, the Scala Guice was activated at the entrance of the project and obtained an instance of binding through the `Scalainjector` extension class.Perform these steps in order, and you can successfully use the Scala Guice framework in the Java class library.