Google Guice的隐藏功能 [英] Hidden Features of Google Guice

查看:133
本文介绍了Google Guice的隐藏功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google Guice提供了一些很大的依赖注入功能。

Google Guice provides some great dependency injection features.

我最近遇到了 @Nullable 功能,允许您将构造函数参数标记为可选(允许null),因为Guice不允许这些参数默认值:

I came across the @Nullable feature recently which allows you to mark constructor arguments as optional (permitting null) since Guice does not permit these by default:

例如

public Person(String firstName, String lastName, @Nullable Phone phone) {
    this.firstName = checkNotNull(firstName, "firstName");
    this.lastName = checkNotNull(lastName, "lastName");
    this.phone = phone;
}

https://github.com/google/guice/wiki/UseNullable

其他的Guice(特别是较不明显的人)使用的有用功能?

What are the other useful features of Guice (particularly the less obvious ones) that people use?

推荐答案

但是这些是我最喜欢的Guice的红利功能:

None of 'em are intended to be hidden, but these are my favorite 'bonus features' in Guice:

  • Guice can inject a TypeLiteral<T>, effectively defeating erasure.
  • TypeLiteral can do generic type resolution: this tells you that get() on a List<String> returns an Iterator<String>.
  • Types is a factory for implementations of Java's generic type interfaces.
  • Grapher visualizes injectors. If your custom provider implements HasDependencies, it can augment this graph.
  • Modules.override() is incredibly handy in a pinch.
  • Short syntax for defining parameterized keys: new Key<List<String>>() {}.
  • Binder.skipSources() lets you to write extensions whose error messages track line numbers properly.
  • The SPI. Elements.getElements() breaks a module into atoms and Elements.getModule() puts them back together.
  • If you implement equals() and hashCode() in a Module, you can install that module multiple times without problem.

这篇关于Google Guice的隐藏功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆