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?
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.
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.
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.
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.
None of 'em are intended to be hidden, but these are my favorite 'bonus features' in Guice:
get()
on a List<String>
returns an Iterator<String>
.new Key<List<String>>() {}
.equals()
and hashCode()
in a Module
, you can install that module multiple times without problem.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With