1. Introduction
In this tutorial, we’ll discuss Guice, Google’s Dependency Injection framework, and how the @Provides annotation differs from Provider classes in Guice.
2. Guice Basics
Google created a lightweight dependency injection(DI) framework called Guice for Java 5 and above. While it’s not as comprehensive a framework as Spring, Guice is feature-rich and aims to make dependency injection simpler.
Guice allows dependencies to be passed in or injected into objects, following the DI pattern in software design. It defines wiring objects using Java code and annotations instead of configurations that some other DI frameworks use.
Guice has the following key components:
- Guice operates heavily on annotations that mark injection points
- Guice has the concept of modules, which define bindings
- Bindings that connect interfaces to actual implementations
- An injector which is in charge of creating and wiring objects
Guice, similar to Spring, supports constructor injection, method injection, and field or parameter injection. We annotate the constructor, module, or field with the @Inject annotation.
Bindings define how Guice should inject dependencies into a class. We define these bindings inside module classes, which are implementations of AbstractModule.
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>7.0.0</version>
</dependency>
3. Provider Classes in Guice
Provider classes are used to manage the object creation process. They’re beneficial when the instantiation process is complex or requires additional logic, which is challenging to manage with dependency injection.
Provider classes implement the com.google.inject.Provider<T> interface, which defines a single T get() method. The implementation of this method returns an instance of the required type.
Let’s understand how we can define and use a Provider class.
3.1. Implementing the Provider Interface
For our example, let’s consider a Notifier interface that notifies clients of events. The Notifier implementations can be of type email or phone:
public interface Notifier {
void sendNotification(String message);
}
We define our EmailNotifier class for this example and make it a Provider<T> class for the Notifier type:
public class EmailNotifier implements Notifier, Provider<Notifier> {
private String smtpUrl;
private String user;
private String password;
private EmailNotifier emailNotifier;
@Override
public Notifier get() {
// perform some initialization for email notifier
this.smtpUrl = "smtp://localhost:25";
emailNotifier = new EmailNotifier();
return emailNotifier;
}
@Override
public void sendNotification(String message) {
log.info("Sending email notification: " + message);
}
}
Notably, we implement com.google.inject.Provider to denote our Provider implementation, and we initialize the provider inside the get() method.
3.2. Binding the Provider to a Type
Now that the Provider is defined, we need to bind this association in our module class. We create our module class by extending from AbstractModule and overriding the configure()Â method:
public class MyGuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(Notifier.class).to(EmailNotifier.class);
}
}
This informs Guice to always call the get() method of EmailNotifier to inject a dependency of Notifier.
Let’s verify the dependency:
@Test
public void givenGuiceProvider_whenInjecting_thenShouldReturnEmailNotifier() {
// Create a Guice injector with the NotifierModule
Injector injector = Guice.createInjector(new NotifierModule());
// Get an instance of Notifier from the injector
Notifier notifier = injector.getInstance(Notifier.class);
// Assert that notifier is of type EmailNotifier
assert notifier != null;
assert notifier instanceof EmailNotifier;
}
While this is a concise way of injecting the dependency of EmailNotifier, it should be noted that this isn’t the best approach, especially when there are multiple implementations of Notifier in the picture.
Let’s consider a second type of Notifier for this example, PhoneNotifier. It’s not allowed by Guice to bind both classes to Notifier in this way.
The solution to that is by using the @Named annotation. The @Named annotation in Guice is a built-in binding annotation used to distinguish between multiple bindings of the same type by associating each binding with a unique string identifier.
When we have both PhoneNotifier and EmailNotifier dependencies to inject, this is what we do:
@Override
protected void configure() {
bind(Notifier.class).annotatedWith(Names.named("Email"))
.toProvider(EmailNotifier.class);
bind(Notifier.class).annotatedWith(Names.named("Phone"))
.toProvider(PhoneNotifier.class);
}
This removes any ambiguity that Guice might face. In our service implementation, we use the name of the implementation to specify which implementation we want Guice to choose:
public class MyService {
private final Notifier emailNotifier;
private final Notifier phoneNotifier;
@Inject
public MyService(@Named("Email") Notifier emailNotifier, @Named("Phone") Notifier phoneNotifier) {
this.emailNotifier = emailNotifier;
this.phoneNotifier = phoneNotifier;
}
}
4. @Provides Annotation in Guice
The @Provides annotation attempts to define a simpler alternative to Provider classes. The @Provides annotation in Guice is designed to annotate methods that can act as binding providers.
The annotation also provides the ability to declare additional dependencies as parameters to the method.
4.1. Implementation of @Provides
A @Provides annotation is always defined within a module class and must be annotated using a method. The method’s return type becomes the bound type in the dependency injection system.
Let’s understand this with a new interface called Logger:
public interface Logger {
void log(String message);
}
With this annotation, a new Provider class becomes unnecessary. We instead add a method in our module class:
@Provides
public Logger provideLogger() {
return new Logger() {
@Override
public void log(String message) {
log.info("Logging message: " + message);
}
};
}
There are two important things to notice here. First, we can define a class which implements the Logger interface, and create a new instance of that class inside this method. However, we simply create an inner anonymous class as a shorter alternative.
Second, there is no need to explicitly declare the binding in the configure() method of the module class.
Let’s verify the dependency here:
@Test
public void givenGuiceProvider_whenInjectingWithProvides_thenShouldReturnCustomLogger() {
Injector injector = Guice.createInjector(new MyGuiceModule());
Logger logger = injector.getInstance(Logger.class);
assert logger != null;
Assertions.assertNotNull(logger.log("Hello world"));
}
5. Differences Between @Provides and Provider
In this section, let’s look at a summary of the differences:
| @Provides |
Provider classes |
| Provides simplicity and is ideal for scenarios which comprises one-off bindings |
Requires more boilerplate code |
| No explicit binding needed; Injector automatically uses the @Provides method |
Requires explicit binding in the module |
| Can be static (more efficient) or instance (can access module fields) |
Always instance-based |
| Best for simple instantiation logic |
Best for complex instantiation logic |
| Less suitable for creating different instances based on runtime conditions |
Well-suited for creating instances based on runtime conditions or third-party integration |
| Not inherently lazy |
Supports lazy instantiation |
5. Conclusion
In this article, we explored Provider classes in Guice and their alternative, the @Provides annotation. These approaches help in dependency injection in Guice. We also discussed the merits and demerits of both approaches.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.