Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we'll examine the fundamentals of Google Guice. Then we'll look at some approaches to completing basic Dependency Injection (DI) tasks in Guice.

We'll also compare and contrast the Guice approach to those of more established DI frameworks, like Spring and Contexts and Dependency Injection (CDI).

This tutorial presumes the reader has an understanding of the fundamentals of the Dependency Injection pattern.

2. Setup

In order to use Google Guice in our Maven project, we'll need to add the following dependency to our pom.xml:

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.1.0</version>
</dependency>

There's also a collection of Guice extensions (we'll cover those a little later) here, as well as third-party modules to extend the capabilities of Guice (mainly by providing integration to more established Java frameworks).

3. Basic Dependency Injection With Guice

3.1. Our Sample Application

We'll be working with a scenario where we design classes that support three means of communication in a helpdesk business: Email, SMS, and IM.

Firstly, let's consider the class:

public class Communication {
 
    @Inject 
    private Logger logger;
    
    @Inject
    private Communicator communicator;

    public Communication(Boolean keepRecords) {
        if (keepRecords) {
            System.out.println("Message logging enabled");
        }
    }
 
    public boolean sendMessage(String message) {
        return communicator.sendMessage(message);
    }

}

This Communication class is the basic unit of communication. An instance of this class is used to send messages via the available communications channels. As shown above, Communication has a Communicator, which we'll use to do the actual message transmission.

The basic entry point into Guice is the Injector:

public static void main(String[] args){
    Injector injector = Guice.createInjector(new BasicModule());
    Communication comms = injector.getInstance(Communication.class);
}

This main method retrieves an instance of our Communication class. It also introduces a fundamental concept of Guice: the Module (using BasicModule in this example). The Module is the basic unit of definition of bindings (or wiring, as it's known in Spring).

Guice has adopted a code-first approach for dependency injection and management, so we won't be dealing with a lot of XML out-of-the-box.

In the example above, the dependency tree of Communication will be implicitly injected using a feature called just-in-time binding, provided the classes have the default no-arg constructor. This has been a feature in Guice since inception, and only available in Spring since v4.3.

3.2. Guice Basic Bindings

Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class.

A binding is defined in an implementation of com.google.inject.AbstractModule:

public class BasicModule extends AbstractModule {
 
    @Override
    protected void configure() {
        bind(Communicator.class).to(DefaultCommunicatorImpl.class);
    }
}

This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.

3.3. Named Binding

Another incarnation of this mechanism is the named binding. Consider the following variable declaration:

@Inject @Named("DefaultCommunicator")
Communicator communicator;

For this, we'll have the following binding definition:

@Override
protected void configure() {
    bind(Communicator.class)
      .annotatedWith(Names.named("DefaultCommunicator"))
      .to(DefaultCommunicatorImpl.class);
}

This binding will provide an instance of Communicator to a variable annotated with the @Named(“DefaultCommunicator”) annotation.

We can also see that the @Inject and @Named annotations appear to be loan annotations from Jakarta EE's CDI, and they are. They're in the com.google.inject.* package, and we should be careful to import from the right package when using an IDE.

Tip: While we just said to use the Guice-provided @Inject and @Named, it's worthwhile to note that Guice does provide support for javax.inject.Inject and javax.inject.Named, among other Jakarta EE annotations.

3.4. Constructor Binding

We can also inject a dependency that doesn't have a default no-arg constructor using constructor binding:

public class BasicModule extends AbstractModule {
 
    @Override
    protected void configure() {
        bind(Boolean.class).toInstance(true);
        bind(Communication.class).toConstructor(
          Communication.class.getConstructor(Boolean.TYPE));
}

The snippet above will inject an instance of Communication using the constructor that takes a boolean argument. We supply the true argument to the constructor by defining an untargeted binding of the Boolean class.

Furthermore, this untargeted binding will be eagerly supplied to any constructor in the binding that accepts a boolean parameter. With this approach, we can inject all dependencies of Communication.

Another approach to constructor-specific binding is the instance binding, where we provide an instance directly in the binding:

public class BasicModule extends AbstractModule {
 
    @Override
    protected void configure() {
        bind(Communication.class)
          .toInstance(new Communication(true));
    }    
}

This binding will provide an instance of the Communication class wherever we declare a Communication variable.

In this case, however, the dependency tree of the class won't be automatically wired. Moreover, we should limit the use of this mode where there isn't any heavy initialization or dependency injection necessary.

4. Types of Dependency Injection

Guice also supports the standard types of injections we've come to expect with the DI pattern. In the Communicator class, we need to inject different types of CommunicationMode.

4.1. Field Injection

@Inject @Named("SMSComms")
CommunicationMode smsComms;

We can use the optional @Named annotation as a qualifier to implement targeted injection based on the name.

4.2. Method Injection

Here we'll use a setter method to achieve the injection:

@Inject
public void setEmailCommunicator(@Named("EmailComms") CommunicationMode emailComms) {
    this.emailComms = emailComms;
}

4.3. Constructor Injection

We can also inject dependencies using a constructor:

@Inject
public Communication(@Named("IMComms") CommunicationMode imComms) {
    this.imComms= imComms;
}

4.4. Implicit Injections

Guice will also implicitly inject some general purpose components, like the Injector and an instance of java.util.Logger, among others. Please note that we're using loggers all through the samples, but we won't find an actual binding for them.

5. Scoping in Guice

Guice supports the scopes and scoping mechanisms we've grown used to in other DI frameworks. Guice defaults to providing a new instance of a defined dependency.

5.1. Singleton

Let's inject a singleton into our application:

bind(Communicator.class).annotatedWith(Names.named("AnotherCommunicator"))
  .to(Communicator.class).in(Scopes.SINGLETON);

The in(Scopes.SINGLETON) specifies that any Communicator field with the @Named(“AnotherCommunicator”) annotation will get a singleton injected. This singleton is lazily initiated by default.

5.2. Eager Singleton

Then we'll inject an eager singleton:

bind(Communicator.class).annotatedWith(Names.named("AnotherCommunicator"))
  .to(Communicator.class)
  .asEagerSingleton();

The asEagerSingleton() call defines the singleton as eagerly instantiated.

In addition to these two scopes, Guice supports custom scopes, as well as the web-only @RequestScoped and @SessionScoped annotations supplied by Jakarta EE (there are no Guice-supplied versions of these annotations).

6. Aspect-Oriented Programming in Guice

Guice is compliant with the AOPAlliance's specifications for aspect-oriented programming. We can implement the quintessential logging interceptor, which we'll use to track message sending in our example in only four steps.

Step 1 – Implement the AOPAlliance's MethodInterceptor:

public class MessageLogger implements MethodInterceptor {

    @Inject
    Logger logger;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object[] objectArray = invocation.getArguments();
        for (Object object : objectArray) {
            logger.info("Sending message: " + object.toString());
        }
        return invocation.proceed();
    }
}

Step 2 – Define a Plain Java Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MessageSentLoggable {
}

Step 3 – Define a Binding for a Matcher:

Matcher is a Guice class that we'll use to specify the components that our AOP annotation will apply to. In this case, we want the annotation to apply to implementations of CommunicationMode:

public class AOPModule extends AbstractModule {

    @Override
    protected void configure() {
        bindInterceptor(
            Matchers.any(),
            Matchers.annotatedWith(MessageSentLoggable.class),
            new MessageLogger()
        );
    }
}

Here we specified a Matcher that will apply our MessageLogger interceptor to any class that has the MessageSentLoggable annotation applied to its methods.

Step 4 – Apply Our Annotation to Our Communication Mode and Load Our Module

@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
    logger.info("SMS message sent");
    return true;
}

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new BasicModule(), new AOPModule());
    Communication comms = injector.getInstance(Communication.class);
}

7. Conclusion

Having looked at basic Guice functionality, we can see where the inspiration for Guice came from Spring.

Along with its support for JSR-330, Guice aims to be an injection-focused DI framework (whereas Spring provides a whole ecosystem for programming convenience, not necessarily just DI) targeted at developers who want DI flexibility.

Guice is also highly extensible, allowing programmers to write portable plugins that result in flexible and creative uses of the framework. This is in addition to the extensive integration that Guice already provides for the most popular frameworks and platforms, like Servlets, JSF, JPA, and OSGi, to name a few.

All of the source code used in this article is available in our GitHub project.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!