Skip to main content

Developing a HK2 module productively

Posted by kohsuke on July 16, 2007 at 5:00 PM PDT

I spent a good portion of the day on HK2 (the rest went to the usual "fix bugs now! I mean NOW!" drill that we all know right before a big release.)

Much of the productivity improvements in HK2 (compared to how GFv2 is done) come from the fact that HK2 comes with a Maven plugin that knows how to build a HK2 module. It's much like how Maven plugin is built by Maven, where all kinds of additional metadata description is geenrated behind the scene for runtime.

The same happens with Maven HK2 plugin. Every time you define a contract and implementations:

@Contract
public interface Animal {
    void bark();
}

@Service(name="pig")
public class Pig implements Animal {
    public void bark() {
        System.out.println("Oink, oink");
    }
}

The build generates the proper META-INF/services files so that the runtime can discover them. The same plugin looks at POM, picks up all the dependencies, and writes that into MAFENIST.MF in the form that the runtime understands.

The plugin does more. When we have a configurable component:

@Configured @Service
public class GenericAnimal implements Animal, Named {
    @FromAttribute
    public String name;
    @FromAttribute
    public String bark;

    public String getName() { return name; }
    public void bark() { System.out.println(bark); }
}

The plugin generates the code that reads XML and populates the object, all behind the scene (this is where I use SXC that I've been hacking lately.) Doing this kind of code generation earlier allows us to run faster (especially start-up time), compared to doing this by reflection at runtime.

All of these are done with minimal intrusion to POM. Basically, all you need to do is to change the from "jar" to "hk2-jar".

The point of this is that with Ant, adding a build step that cuts across all the modules has been fairly tedious, but Maven allows us to add all sorts of complex processing to the module build process, without exposing them to the module developers. IOW, two or three real Maven gurus of the Glassfish team can do all the hard work, and the rest of the Glassfish team can enjoy the improved productivity and spend less time on build script.

The challenge that remains to be seen is whether this gain will outweigh the cost of using Maven, which is known to produce cryptic error messages and to be unforgiving to inproper ~/.m2/settings.xml, but I'm optimistic.

You can see more info at the updated HK2 site.

Related Topics >>