Monday, February 27, 2012

Update for hello-world-hk2-sample

Take a look at Sahoo's hello-world-hk2-sample part I, updated for hk2 version 1.6.30.

I also extended it with support for Configuration, which is another very interesting part of HK2.

You can find sources at GitHub.

Important points to notice:

1) DomainXml as starting point for configuration. Mainly it is Populator, so with help of ConfigParser.parse it populates habitat with hk2 configuration beans habitants.

2) Named configuration beans:

Domain extends ... Named, so that it can be looked up by name, e.g.

@Inject(name="test")
Domain domain;
or
habitat.getComponent(Domain.class, "test2");
3) And Transactions support (modifiable configuration), for which it's necessary to override DomDocument.make() method to produce ConfigBean objects instead of Dom.

public class MyDocument extends DomDocument<configbean> {
    public MyDocument(final Habitat habitat) {
        super(habitat);
    }
    
    @Override
    public ConfigBean make(final Habitat habitat, XMLStreamReader xmlStreamReader,
            ConfigBean dom, ConfigModel configModel) {
        // by default, people get the translated view.
        return new ConfigBean(habitat,this, dom, configModel, xmlStreamReader);
    }

}

Then use it in DomainXml.run() method for ConfigParser:

parser.parse(res, new MyDocument(habitat));

That's all so far, but it may be updated for persisting configuration modifications.

No comments: