eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)