Scala + Guice + Gradle (Part 2)

In Part 1 of this tutorial I showed you how to create a Gradle based Scala project. Now I will show you how to use Guice.

Basic example

The abstraction that defines the contract:
package me.m1key.audioliciousmigration

trait AudioliciousImporter {

def importLibrary(libraryUuid: String): Unit

The implementation:
package me.m1key.audioliciousmigration.importer

import me.m1key.audioliciousmigration.AudioliciousImporter

class RelativeDataImporter extends AudioliciousImporter {

def importLibrary(libraryUuid: String): Unit = {
    println("Importing library [%s]...".format(libraryUuid));
    println("Library [%s] imported.".format(libraryUuid));

Note package level private access - the implementation is not visible from the outside.

Here we bind implementations to abstractions:

package me.m1key.audioliciousmigration
import com.google.inject.AbstractModule
import com.google.inject.Provides
import me.m1key.audioliciousmigration.importer.RelativeDataImporter

class AudioliciousMigrationModule extends AbstractModule {

protected def configure() {

Finally, the bootstrap:
package me.m1key.audioliciousmigration
import com.google.inject.Guice

object Launcher {

def main(args: Array[String]): Unit = {
    println("Audiolicious Importer")
    val injector = Guice.createInjector(new AudioliciousMigrationModule)
    val importer = injector.getInstance(classOf[AudioliciousImporter])

If you're new to Guice and you're confused, you can read more about it here.

In Part 3 I will show you how to create a singleton.

Download source code

Source code for this article can be obtained via GitHub.

No comments:

Post a Comment