Book Image

Learning Google Guice

By : Hussain Pithawala
Book Image

Learning Google Guice

By: Hussain Pithawala

Overview of this book

<p>Google Guice is an open source software framework for the Java platform released by Google under the Apache License. It provides support for dependency injection using annotations to configure Java objects.</p> <p>Learning Google Guice is a concise, hands-on book that covers the various areas of dependency injection using the features provided by the latest version of Google Guice. It focuses on core functionalities as well as the various extensions surrounding Guice that make it useful in other areas like web development, integration with frameworks for web development, and persistence.</p> <p>Learning Google Guice covers Guice extensions which avoid complex API usage. You will start by developing a trivial application and managing dependencies using Guice. As the book gradually progresses, you will continue adding complexity to the application while simultaneously learning how to use Guice features such as the Injector, Provider, Bindings, Scopes, and so on. Finally, you will retrofit the application for the Web, using Guice not only to manage dependencies, but also to solve configuration related problems.</p>
Table of Contents (17 chapters)
Learning Google Guice
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Static injection


There are certain cases where in static attributes need to be dependency injected. Let us consider one such case. FlightUtils is a utility class providing a static method parseDate to parse a String in a given format and return the date. The format String is hardcoded in this API. Let us try to inject it statically.

Let us create a private static String attribute dateFormat and create its getter and setter. Mark the setter for injection with a @Named parameter.

@Inject
public static void setDateFormat(
   @Named("df")String dateFormat){ 
   FlightUtils.dateFormat = dateFormat;
}

Next, prepare a module for FlightUtils:

class FlightUtilityModule extends AbstractModule{ 
  @Override 
  protected void configure() {
    bindConstant().annotatedWith(
    Names.named(dateFormat)).to(dd-MM-yy);
    requestStaticInjection(FlightUtils.class);
  }
}

Static injection comes into picture, (if requested) immediately once the injector instance is returned. Hence, we need not invoke the .getInstance...