Introduction to Guice

I hope to make this place my secret garden to track my technique growth.
This is my first post. Simple notes about Google Guice.

Guice Logo

What is Guice

The best resource is always the official website.

Think of Guiceā€™s @Inject as the new new.
Guice can build the object graph.

Linked Bindings

Map a type to its implementation.

1
2
3
4
5
6
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
}
}

When you call injector.getInstance(TransactionLog.class), or when the injector encounters a dependency on TransactionLog, it will use a DatabaseTransactionLog.

@Provides Methods

To create an object. Must be defined within a module.

Scopes

By default, Guice returns a new instance each time it supplies a value.

@Singleton :to reuse instances for the lifetime of an application

Typical Example:

1
2
3
4
@Provides @Singleton
TransactionLog provideTransactionLog() {
...
}

Injections

Constructor Injection: annotate the constructor with the @Inject annotation
Method/Field Injection

Injection Example

A simple inject example:

https://github.com/AudreyMeng/Java/tree/master/guiceTest1

To @inject Communicator implementation field in Communication:

  1. guiceStart createInjector for BasicModule and getInstance ->

  2. BasicModule extends AbstractModule,

  3. in BasicModule.configure method binds Communicator to Communication ->

  4. Communication class @inject a Communicator

References

https://github.com/google/guice