Guice 快速入门

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Guice是谷歌推出的一个轻量级依赖注入框架,帮助我们解决Java项目中的依赖注入问题。如果使用过Spring的话,会了解到依赖注入是个非常方便的功能。不过假如只想在项目中使用依赖注入,那么引入Spring未免大材小用了。

Guice是谷歌推出的一个轻量级依赖注入框架,帮助我们解决Java项目中的依赖注入问题。如果使用过Spring的话,会了解到依赖注入是个非常方便的功能。不过假如只想在项目中使用依赖注入,那么引入Spring未免大材小用了。这时候我们可以考虑使用Guice。本文参考了Guice官方文档,详细信息可以直接查看Guice文档

基本使用

引入依赖

如果使用Maven的话,添加下面的依赖项。

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

如果使用Gradle的话,添加下面的依赖项。

compile group: 'com.google.inject', name: 'guice', version: '4.1.0'

当构建工具解决完项目的依赖之后,我们就可以开始使用Guice了。

项目骨架

首先我们来假设一个简单的项目框架。首先我们需要一个业务接口,简单的包含一个方法用于执行业务逻辑。它的实现也非常简单。

public interface UserService {
    void process();
}

public class UserServiceImpl implements UserService {
    @Override
    public void process() {
        System.out.println("我需要做一些业务逻辑");
    }
}

然后我们需要一个日志接口,它和它的实现也非常简单。

public interface LogService {
    void log(String msg);
}

public class LogServiceImpl implements LogService {
    @Override
    public void log(String msg) {
        System.out.println("------LOG:" + msg);
    }
}

最后是一个系统接口和相应的实现。在实现中我们使用了业务接口和日志接口处理业务逻辑和打印日志信息。

public interface Application {
    void work();
}

public class MyApp implements Application {
    private UserService userService;
    private LogService logService;

    @Inject
    public MyApp(UserService userService, LogService logService) {
        this.userService = userService;
        this.logService = logService;
    }

    @Override
    public void work() {
        userService.process();
        logService.log("程序正常运行");
    }
}

简单的依赖注入

首先来配置依赖关系。我们继承AbstractModule类,并重写configure方法即可。在configure方法中,我们可以调用AbstractModule类提供的一些方法来配置依赖关系。最常用的方式就是bind(接口或父类).to(实现类或子类)的方式来设置依赖关系。

public class MyAppModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(LogService.class).to(LogServiceImpl.class);
        bind(UserService.class).to(UserServiceImpl.class);
        bind(Application.class).to(MyApp.class);
    }
}

这样一来,当Guice遇到接口或父类需要注入具体实现的时候,就会使用这里配置的实现类或子类来注入。如果希望在构造器中注入依赖的话,只需要添加@Inject注解即可。

Guice配置完之后,我们需要调用Guice.createInjector方法传入配置类来创建一个注入器,然后使用注入器的getInstance方法获取目标类,Guice会按照配置帮我们注入所有依赖。我们使用单元测试来看看效果。

public class MyAppTest {
    private static Injector injector;

    @BeforeClass
    public static void init() {
        injector = Guice.createInjector(new MyAppModule());
    }

    @Test
    public void testMyApp() {
        Application myApp = injector.getInstance(Application.class);
        myApp.work();
    }
}

//程序结果
//我需要做一些业务逻辑
//------LOG:程序正常运行

依赖绑定

下面这些例子都是Guice文档上的例子。我算是简单的翻译了一下。

链式绑定

我们在绑定依赖的时候不仅可以将父类和子类绑定,还可以将子类和更具体的子类绑定。下面的例子中,当我们需要TransactionLog的时候,Guice最后会为我们注入MySqlDatabaseTransactionLog对象。

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
  }
}

注解绑定

当我们需要将多个同一类型的对象注入不同对象的时候,就需要使用注解区分这些依赖了。最简单的办法就是使用@Named注解进行区分。

首先需要在要注入的地方添加@Named注解。

public class RealBillingService implements BillingService {

  @Inject
  public RealBillingService(@Named("Checkout") CreditCardProcessor processor,
      TransactionLog transactionLog) {
    ...
  }

然后在绑定中添加annotatedWith方法指定@Named中指定的名称。由于编译器无法检查字符串,所以Guice官方建议我们保守地使用这种方式。

    bind(CreditCardProcessor.class)
        .annotatedWith(Names.named("Checkout"))
        .to(CheckoutCreditCardProcessor.class);

如果希望使用类型安全的方式,可以自定义注解。

@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PayPal {}

然后在需要注入的类上应用。

public class RealBillingService implements BillingService {

  @Inject
  public RealBillingService(@PayPal CreditCardProcessor processor,
      TransactionLog transactionLog) {
    ...
  }

在配置类中,使用方法也和@Named类似。

    bind(CreditCardProcessor.class)
        .annotatedWith(PayPal.class)
        .to(PayPalCreditCardProcessor.class);

实例绑定

有时候需要直接注入一个对象的实例,而不是从依赖关系中解析。如果我们要注入基本类型的话只能这么做。

    bind(String.class)
        .annotatedWith(Names.named("JDBC URL"))
        .toInstance("jdbc:mysql://localhost/pizza");
    bind(Integer.class)
        .annotatedWith(Names.named("login timeout seconds"))
        .toInstance(10);

如果使用toInstance方法注入的实例比较复杂的话,可能会影响程序启动。这时候可以使用@Provides方法代替。

@Provides方法

当一个对象很复杂,无法使用简单的构造器来生成的时候,我们可以使用@Provides方法,也就是在配置类中生成一个注解了@Provides的方法。在该方法中我们可以编写任意代码来构造对象。

public class BillingModule extends AbstractModule {
  @Override
  protected void configure() {
    ...
  }

  @Provides
  TransactionLog provideTransactionLog() {
    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
    transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
    transactionLog.setThreadPoolSize(30);
    return transactionLog;
  }
}

@Provides方法也可以应用@Named和自定义注解,还可以注入其他依赖,Guice会在调用方法之前注入需要的对象。

  @Provides @PayPal
  CreditCardProcessor providePayPalCreditCardProcessor(
      @Named("PayPal API key") String apiKey) {
    PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
    processor.setApiKey(apiKey);
    return processor;
  }

Provider绑定

如果项目中存在多个比较复杂的对象需要构建,使用@Provide方法会让配置类变得比较乱。我们可以使用Guice提供的Provider接口将复杂的代码放到单独的类中。办法很简单,实现Provider<T>接口的get方法即可。在Provider类中,我们可以使用@Inject任意注入对象。

public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {
  private final Connection connection;

  @Inject
  public DatabaseTransactionLogProvider(Connection connection) {
    this.connection = connection;
  }

  public TransactionLog get() {
    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
    transactionLog.setConnection(connection);
    return transactionLog;
  }
}

在配置类中使用toProvider方法绑定到Provider上即可。

public class BillingModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(TransactionLog.class)
        .toProvider(DatabaseTransactionLogProvider.class);
  }

作用域

默认情况下Guice会在每次注入的时候创建一个新对象。如果希望创建一个单例依赖的话,可以在实现类上应用@Singleton注解。

@Singleton
public class InMemoryTransactionLog implements TransactionLog {
  /* everything here should be threadsafe! */
}

或者也可以在配置类中指定。

bind(TransactionLog.class).to(InMemoryTransactionLog.class).in(Singleton.class);

@Provides方法中也可以指定单例。

  @Provides @Singleton
  TransactionLog provideTransactionLog() {
    ...
  }

如果一个类型上存在多个冲突的作用域,Guice会使用bind()方法中指定的作用域。如果不想使用注解的作用域,可以在bind()方法中将对象绑定为Scopes.NO_SCOPE

Guice和它的扩展提供了很多作用域,有单例Singleton,Session作用域SessionScoped,Request请求作用域RequestScoped等等。我们可以根据需要选择合适的作用域。

Servlet集成

Guice也可以和Servlet项目集成,这样我们就可以不用编写冗长的web.xml,以依赖注入的方式使用Servlet和相关组件。

安装Guice Servlet扩展

要在Servlet项目中集成Guice,首先需要安装Guice Servlet扩展。如果使用Maven,添加下面的依赖。

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

如果使用Gradle,添加下面的依赖。

compile group: 'com.google.inject.extensions', name: 'guice-servlet', version: '4.1.0'

添加依赖之后,在web.xml中添加下面的代码,让Guice过滤所有web请求。

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

配置Injector

和普通的项目一样,Servlet项目同样需要配置Injector。一种比较好的办法就是在ContextListener中配置Injector。Guice的Servlet集成提供了GuiceServletContextListener,我们继承该类并在getInjector方法中配置Injector即可。

public class MyGuiceServletConfigListener extends GuiceServletContextListener {

  @Override
  protected Injector getInjector() {
    return Guice.createInjector(new ServletModule());
  }
}

当然仅仅继承GuiceServletContextListener还是不够的。我们还需要在web.xml中添加几行代码。

<listener>
    <listener-class>yitian.study.servlet.MyGuiceConfigListener</listener-class>
</listener>

配置Servlet和过滤器

默认的ServletModule就会启用一些功能。如果需要自定义Servlet和Filter,就需要继承ServletModule并重写configureServlets()方法。配置Servlet和Filter的方法和配置普通依赖注入类似。

public class MyServletConfig extends ServletModule {
    @Override
    protected void configureServlets() {
        serve("/*").with(MainServlet.class);
        filter("/*").through(CharEncodingFilter.class);
    }
}

然后将ServletModule替换为我们自己的实现类。

public class MyGuiceConfigListener extends GuiceServletContextListener {

    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new MyServletConfig());
    }
}

注入Servlet相关对象

除了配置Servlet之外,Guice还允许我们把Request、Response和Session对象注入到非Servlet对象中。下面是Guice的一个例子。

@RequestScoped
class SomeNonServletPojo {

  @Inject
  SomeNonServletPojo(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    ...
  }

}

我们还可以使用Guice注入请求参数。下面这个类的作用是获取所有请求参数并转换为字符串形式。

@RequestScoped
public class Information {
    @Inject
    @RequestParameters
    Map<String, String[]> params;

    public String getAllParameters() {
        return params.entrySet()
                .stream()
                .map(entry -> entry.getKey() + " : " + Arrays.toString(entry.getValue()))
                .collect(Collectors.joining(", "));
    }
}

之后,我们就可以将该对象注入到Servlet中使用,将结果返回给页面。

@Singleton
public class MainServlet extends HttpServlet {
    @Inject
    private Injector injector;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        req.setAttribute("name", name);
        Information info = injector.getInstance(Information.class);
        req.setAttribute("params", info.getAllParameters());
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

}

Guice Servlet扩展还有其他功能,这里就不在列举了。详情请参看Guice文档。

JSR-330标准

JSR-330是一项Java EE标准,指定了Java的依赖注入标准。Spring、Guice和Weld等很多框架都支持JSR-330。下面这个表格来自于Guice文档,我们可以看到JSR-330和Guice注解基本上可以互换。

JSR-330 javax.inject Guice com.google.inject
@Inject @Inject 在某些约束下可互换
@Named @Named 可互换
@Qualifier @BindingAnnotation 可互换
@Scope @ScopeAnnotation 可互换
@Singleton @Singleton 可互换
Provider Provider Guice的Provider继承了JSR-330的Provider

Guice官方推荐我们首选JSR-330标准的注解。

以上就是Guice的基本知识了。如果需要更详细的使用方法,请参考Guice文档。如果有兴趣还可以看看我的CSDN代码,包含了我的Guice练习代码。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
|
Java 应用服务中间件 API
Webflux快速入门
Webflux快速入门
|
11月前
|
负载均衡 Java API
【java_wxid项目】【第四章】【Spring Cloud Ribbon集成】
【java_wxid项目】【第四章】【Spring Cloud Ribbon集成】
|
NoSQL Java API
【直播预告】:Java Spring Boot开发实战系列课程【第15讲】:Spring Boot 2.0 API与Spring REST Docs实战
基于Java Spring Boot 2.0可以快速开发REST API,但是如何根据API自动生成 Help Docs是非常重要的问题。本次课程详细介绍几种不同的Rest Help Docs的构建方式,核心原理与区别。
2040 0
|
Java 测试技术 Maven
bboss ioc快速入门教程
    bboss是一个非常不错的ioc框架,功能类似于spring ioc和google guice,本文结合一个简单的案例来介绍bboss ioc的用法,让你快速的了解和上手使用bboss ioc。
987 0