Guide to Google Guice


Why Dependency Injection

  • don’t create it, ask for it.
  • decouples classes
  • make unit testing easier

Guice vs Dagger

Guice is base on reflection, while Dagger is generating extra code during compile-time; reflection is much slower than the pre-generated code

Types of Dependency Injection

  • Constructor Injection
    • preferred: as it minimize mutability
    • use private final fields.
  • Method Injection
  • Don’t use Field Injection
    • difficult to test
    • field can’t be final

AbstractModule

  • bind(Interface.class).to(Implementation.class)
  • bind().toInstance()

Injector

  • One injector per application.

@Qualifier

@Named

  • discouraged due to potential typos, difficult to refactor: change the names, can’t restrict the access
  • prefer custom @Qualifier annotations to @Named

@Provides Methods

  • @Provides methods can have parameters that are injected by Guice
  • @Provides methods will be called each time the dependency is requested

@Singleton

  • By default, Guice will create a new instance for each dependency it injects
  • Avoid singleton when possible
  • To create a singleton instance:
    • Add @Singleton to the class or the @Provides method
    • bind().to().in(Singleton.class);

@RequestScoped, @SessionScoped

  • Don’t use scope unless have to

Implicit binding vs explicit binding

  • Bindings present in binding module are called explicit bindings and are of higher precedence.
  • just-in-time bindings are called implicit bindings. If both type of bindings are present, explicit bindings are considered for mapping.
    • a non-private, no-arguments constructor, or a constructor with the @Inject annotation
    • @ImplementedBy
    • @ProvidedBy

Best Practices

Resources

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)