Guice Grapher - Example

Guice provides a 'Grapher' module, as an extension to its framework, to visualize the bindings and the application structure. This module is not yet available in the guice-2.0 version (and is not packed in any of the jar files of this version), but you can download the source code from the Guice's SVN repository and build it for use.

Guice's Grapher module finds all the bindings used for a particular injector and generates a DOT file (plain text graph description language). If you have already installed 'GraphViz', you can use the GVEdit.exe to run these DOT files and generate the schematic of an application using Guice's bindings.

For the example from my other post, I just copied all the sources under 'com.google.inject.grapher', built my project and ran the main java class, which looks as below:

package com.chetty.client;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import com.chetty.module.MathModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.grapher.GrapherModule;
import com.google.inject.grapher.InjectorGrapher;
import com.google.inject.grapher.graphviz.GraphvizModule;
import com.google.inject.grapher.graphviz.GraphvizRenderer;

public class MathApp {
public static void main(String[] args) throws IOException {
Injector injector = Guice.createInjector(new MathModule());

MathClient mathClient = injector.getInstance(MathClient.class);

mathClient.sumOfAllConsecutiveNumbers(1000);

PrintWriter out = new PrintWriter(new File("c://MathAppGraph.dot"), "UTF-8");

Injector graphInjector = Guice.createInjector(new GrapherModule(), new GraphvizModule());
GraphvizRenderer renderer = graphInjector.getInstance(GraphvizRenderer.class);
renderer.setOut(out).setRankdir("TB");

graphInjector.getInstance(InjectorGrapher.class)
.of(injector)
.graph();
}
}


Running this class, generated a DOT file, which when opened with GraphViz's Editor, looks like:



The above pic, generated from my example project doesn't show much. So, lets use the example bundled with the Guice Source code (under 'extensions'). Using this example, the grapher modules, generates the DOT file, for the following pic:

2 comments:

  1. I got exactly the same pictures with several classes missing. The easy user solution is to replace "invis" to "solid" in .dot file. Probably some small bug..

    ReplyDelete
  2. Thanks Anonymous. The replacement solved the issue.

    I've got a question:

    Grapher sometimes do not escape generics (MyClass<...<...>>). And the name of a class prevents parsing of dot file.

    Do someone know how to make grapher produce proper escaping for names?

    ReplyDelete