Guide to Google Guice – Google Guice指南

最后修改: 2017年 3月 14日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

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

2.设置

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中添加以下依赖。

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

还有一系列Guice扩展(我们稍后将介绍这些扩展)这里,以及作为第三方模块来扩展Guice的功能(主要是通过提供与更成熟的Java框架的集成)。

3. Basic Dependency Injection With Guice

3.使用Guice的基本依赖注入

3.1. Our Sample Application

3.1.我们的应用样本

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.

我们将在一个场景下工作,设计支持服务台业务中三种通信手段的类。电子邮件、SMS和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.

这个通信类是通信的基本单位。这个类的一个实例被用来通过可用的通信通道发送消息。如上所示,Communication有一个Communicator,我们将用它来完成实际的消息传输。

The basic entry point into Guice is the Injector:

Guice的基本入口是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).

这个主方法检索了我们的Communication类的一个实例。它还介绍了Guice的一个基本概念:Module(本例中使用BasicModule)。Module是定义绑定的基本单位(或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.

Guice采用了代码优先的方法来进行依赖注入和管理,因此我们将不会在开箱后处理大量的XML。

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

3.2.Guice基本绑定

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

绑定对于Guice来说就像布线对于Spring一样。通过绑定,我们定义了Guice如何将依赖关系注入一个类中。

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

绑定被定义在 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.

这个模块的实现指定在发现DefaultCommunicatorImpl变量的地方注入一个Communicator的实例。

3.3. Named Binding

3.3.命名绑定

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.

这种绑定将为一个用@Named(“DefaultCommunicator”)注解的变量提供一个Communicator的实例。

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.

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

3.4.构造函数绑定

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.

上面的片段将使用构造函数注入一个Communication的实例,该构造函数需要一个boolean参数。我们通过定义非目标绑定Boolean类,向构造函数提供true参数。

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.

此外,这个非目标绑定将被急切地提供给绑定中任何接受boolean参数的构造器。通过这种方法,我们可以注入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.

这个绑定将提供一个Communication类的实例,无论我们在哪里声明一个Communication变量。

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

4.依赖注入的类型

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.

Guice也支持我们所期待的DI模式的标准注入类型。在Communicator类中,我们需要注入不同类型的CommunicationMode

4.1. Field Injection

4.1.领域注入

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

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

我们可以使用可选的@Named注解作为限定符来实现基于名称的定向注入。

4.2. Method Injection

4.2.方法注入

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

这里我们将使用一个setter方法来实现注入。

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

4.3. Constructor Injection

4.3.构造函数注入

We can also inject dependencies using a constructor:

我们也可以使用构造函数注入依赖关系。

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

4.4. Implicit Injections

4.4.隐式注射

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.

Guice也会隐含地注入一些通用组件,比如Injectorjava.util.Logger的实例,等等。请注意,我们在样本中一直在使用记录器,但我们不会为它们找到一个实际的绑定。

5. Scoping in Guice

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

Guice支持我们在其他DI框架中已经习惯的作用域和范围机制。Guice默认为提供一个已定义的依赖的新实例。

5.1. Singleton

5.1.单子

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.

in(Scopes.SINGLETON)指定任何带有@Named(“AnotherCommunicator”)注解的Communicator域将被注入一个单子。这个单子在默认情况下是懒散地启动的。

5.2. Eager Singleton

5.2.急切的单子

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.

asEagerSingleton()调用将单子定义为急于实例化的。

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

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

Guice符合AOPAlliance的面向方面编程的规范。我们可以实现典型的日志拦截器,在我们的例子中,我们将用它来跟踪消息的发送,只需四个步骤。

Step 1 – Implement the AOPAlliance’s MethodInterceptor:

第1步–实现AOPAlliance的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:

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

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

Step 3 – Define a Binding for a Matcher:

第3步–为匹配器定义一个绑定:

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 {

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

这里我们指定了一个Matcher,它将把我们的MessageLogger拦截器应用到任何类上,这些类的方法都有MessageSentLoggable注解。

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

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

@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

7.结论

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

看过Guice的基本功能后,我们可以看到Guice的灵感来自于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.

除了对JSR-330的支持外,Guice旨在成为一个以注入为重点的DI框架(而Spring提供了整个编程便利性的生态系统,不一定只是DI),针对的是那些希望获得DI灵活性的开发人员。

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.

本文中使用的所有源代码都可以在我们的GitHub项目中找到。