• Home
  • Events
  • About
  • GWT Dependency Injection recipes using GIN

    Dependency Injection is already a well-known and discussed topic in the Java world and there are a good number of well established frameworks and libraries supporting this concept. While for many developers it is a must, some others seem not to be so convinced and think that it does not bring that much value to a project. Of course, it depends on the project, but with the time, it seems that its benefits have been widely accepted and support for it has been incorporated in almost every piece of software where it seemed to make sense.

    This is also the case of Google Web Toolkit where GIN provides dependency injection support on the client side.
    GIN is a mainly a GWT-based version of the Google’s homegrown dependency injection framework GUICE. But because the GWT applications run on top of the browser JavaScript engine instead of on the JVM, some of the GUICE features are not available in GIN. On the other hand, GWT provides some poweful features for code generation that have enabled a meaningful subset of the GUICE features to be implemented in GWT.

    Instead of writing an introduction tutorial to the GIN capabilities, the purpose of this article series is to illustrate some of the GIN features while applying some recipes to an existing application.

    Maybe you already know this little screencast where Hamlet D’Arcy explains how to decouple GWT components by mean of an “event bus” in a little “ping-pong” simulation. If not, maybe you would like to spend five minutes watching the screencast and, once you are done, read on and learn how to apply some dependency injection techniques to improve this little application.

    The source code of the application can be downloaded here. To see the application working, unzip the file, change to the folder where the Maven pom file is stored and type the command: “mvn clean gwt:run”. After the GWT “Development mode” application starts, click on the “Launch Default Browser” button.

    Adding GIN to the application

    In order to start using GIN in the sample application, the first task that we should accomplish is adding the GIN dependencies to the project. Because the build of the application is Maven-based, we need simply to add the following dependency to the Maven pom file:

    Note: If you experience issues while using GIN 1.5 with GWT versions previous to 2.2, consider using GIN 1.0. With GWT version 2.2 and superior ones use GIN 1.5 instead.

    Ok, and what now? First, let’s have a look at the “main” class of our GWT application, the “Simulator” class:

    The first “dependency” that we can identify here is the “event bus”. Because an event bus is heavily used in a GWT application to enable component communication with low coupling, it would be an improvement to avoid instantiating the event bus explicitly and having to expose the unique instance used in some class (“singleton”). To achieve this, we need to create two new elements: the GIN injector and at least one GIN module.
    The GIN injector is an interface that will be instantiated by mean of the GWT deferred binding functionality (“GWT.create()” factory method) and that basically declare the “managed beans” of our GWT application. These are the dependencies that can be directly accessed using an instance of the injector or that will be used by the injector to satisfy required dependencies while performing injection:

    The “InjectorModule” class referred in the “@GinModules” annotation is the so called “GIN Module”. In this class, we will configure how the instances of the managed beans should be created:

    Having a look at both files, it is not difficult to understand what we are doing. In the injector and by mean of the “getEventBus” method, we have declared an injectable dependency of the interface type “EventBus”. In the module and by mean of the GIN Java DSL, we have provided an implementation for the dependency and also specified that, no matter how many times we call the “getEventBus” method in the injector, always the same unique instance should be returned. This is also part of the dependency injection configuration process and is sometimes referred as “scope binding”.
    Please, take care of not using different injector instances within the application because, in that case, you would get different event bus instances (one per injector instance).

    Let’s see now how to use the injector in the “Simulator” class to perform the injection:

    If you compare this new version of the “Simulator” class with the previous one, there is not yet a major improvement in the code structure and not even a reduction in the number of code lines. The main improvement so far, is that the instantiation of the event bus is configured in a central point and that the implementation selected is not known outside this configuration class. Anyway, nothing that cannot be done with a simple “factory” class.
    Where comes then the benefit of using dependency injection? OK, let’s know move the instantiation of the “view components” to the injector. For this, adjust the classes in the following way:

    Then, in the “Simulator” class, use the injector to also create the views like this:

    If the “PingView” and “PongView” classes had a default constructor, it would suffice with the previous two changes for the application to work normally. GIN would be, in that case, smart enough to find the classes and create the instances. But, because that is not the case and both classes expect a communication event bus passed as parameter in the constructor, we need to annotate the constructor with the “@Inject” annotation. Then, GIN will try to resolve the parameters in the constructor using a simple dependency resolution mechanism: if there is a method in the injector interface that returns the class of the parameter, this method will be used to obtain an instance of that class. If there is not such a declared method in the injector, but the parameter class has a default constructor, a new instance will then be instantiated. The little detail here is that the instantiation will be done using GWT deferred binding (“GWT.create()” factory method), giving GWT the possibility of “enhancing” the code, instead of simply using the default constructor of the class.
    This way, if every of the constructor parameters can be resolved as dependencies (fulfill at least one of the previous conditions), GIN can create an instance with its dependencies injected and without requiring additional configuration.

    To make the application work, add the “@Inject” annotation to the constructors of both view components as shown in this example:

    Note: GUICE, and therefore GIN, support the JSR-330 standard annotations for dependency injection (package: javax.inject.*) which should be a preferred option in comparison to proprietary annotations with the same semantic but defined in non-standard packages (package: com.google.inject.*). This makes possible to re-arrange the dependencies without changing the code (the type will be loaded from the classpath without being relevant in which JAR file or classpath entry it is located).

    With these changes in the sample application, we have learnt:

    • how to configure GIN using an injector interface and a module class.
    • How to define a first dependency: the event bus.
    • How to select an implementation for the dependency: the “SimpleEventBus” class.
    • How to bind this dependency to a context: the application context in this case (also referred sometimes as “singleton scope”).
    • And finally, how to get the dependency injected in a constructor (what is only one of the many ways of doing dependency injection in GIN).

    For this series of articles, we chose intentionally a simple application where to apply some simple dependency injection recipes. If you are not yet convinced of its benefits, don’t abandon yet! We have just started and in the following articles, we will explore some other possibilities and use cases.

    I hope that you enjoyed reading the article and also to see you in the next part.

    The other parts of this series can be found here and here.

    The source code of the dependency-enabled application can be downloaded here. To execute the application, simply follow the same steps described above for the initial version.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • DZone
    • Y!GG
    • Webnews
    • Digg
    • del.icio.us
    • DotNetKicks
    • Facebook
    • Google Bookmarks
    • Newsrider
    • Twitter
    • YahooBuzz

    1 Comment »

    1. Roland said,

      April 6, 2011 @ 7:32

      Thanks Alberto!

    RSS feed for comments on this post · TrackBack URI

    Leave a Comment

    two + 6 =