Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden Features of Google Guice [closed]

Google Guice provides some great dependency injection features.

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:

e.g.

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

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

like image 422
Jon Avatar asked Apr 26 '10 21:04

Jon


People also ask

Is Guice lazy?

When does guice make the dependencies available? In general, construction is lazy (for non-singleton classes, this is intuitive - you don't know you need a new instance until someone tells you to inject one somewhere). The exception is for eager singletons which are constructed (wait for it) eagerly.

Which is better Guice or Spring?

Spring allows you to omit the @Autowired annotation when there's only one constructor. Guice allows binding to a Provider, as well as injecting a Provider of your class, even when your class has no Provider binding.

Why do we need Guice?

Guice manages its dependencies in a special class called a module. A Guice module has to extend the AbstractModule class and override its configure() method. Guice uses binding as the equivalent to wiring in Spring. Simply put, bindings allow us to define how dependencies are going to be injected into a class.

What does @inject do in Guice?

Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.


1 Answers

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.
like image 62
Jesse Wilson Avatar answered Sep 28 '22 20:09

Jesse Wilson