Guide to Google Guice – Google Guice指南

最后修改: 2017年 3月 14日

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.

在本教程中,我们将研究Google Guice的基础知识。然后我们将看看在Guice中完成基本依赖注入(DI)任务的一些方法。

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

我们还将把Guice的方法与那些更成熟的DI框架,如Spring和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:

为了在我们的Maven项目中使用Google Guice,我们需要在pom.xml中添加以下依赖。


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 {
    private Logger logger;
    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.

在上面的例子中,Communication的依赖树将使用just-in-time binding的特性被隐式注入,前提是这些类有默认的无参数构造函数。这是自Guice成立以来的一项功能,从v4.3开始才在Spring中使用。

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


public class BasicModule extends AbstractModule {
    protected void configure() {

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:


protected void configure() {

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* package, and we should be careful to import from the right package when using an IDE.

我们还可以看到,@Inject @Named注解似乎是从Jakarta EE的CDI中借来的注解,而它们确实如此。它们在*包中,在使用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.

提示:虽然我们刚才说要使用Guice提供的@Inject@Named,但值得注意的是Guice确实提供了对javax.inject.Injectjavax.inject.Named等Jakarta EE注释的支持。

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 {
    protected void configure() {

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 {
    protected void configure() {
          .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:


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

4.3. Constructor Injection


We can also inject dependencies using a constructor:


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:



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:



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

除了这两个作用域之外,Guice还支持自定义作用域,以及Jakarta EE提供的仅适用于Web的@RequestScoped@SessionScoped注解(这些注解没有Guice提供的版本)。

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 {

    Logger logger;

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

Step 2 – Define a Plain Java Annotation:

第2步 – 定义一个普通的Java注释

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:

Matcher 是一个Guice类,我们将用它来指定我们的AOP注解将适用的组件。在这种情况下,我们希望注解适用于CommunicationMode:的实现。

public class AOPModule extends AbstractModule {

    protected void configure() {
            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

第4步 – 将我们的注释应用于我们的通信模式并加载我们的模块</strong

public boolean sendMessage(String message) {"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.

Guice 还具有高度的可扩展性,允许程序员编写可移植的插件,从而实现对该框架的灵活和创造性使用。除此之外,Guice还为最流行的框架和平台提供了广泛的集成,如Servlets、JSF、JPA和OSGi等,仅此而已。

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