dev@glassfish.java.net

Re: question on _at_Extract, _at_Inject, annotations

From: Sahoo <Sahoo_at_Sun.COM>
Date: Fri, 18 Jan 2008 09:33:11 +0530

Lloyd L Chambers wrote:
> Kosuke et al,
>
> [I think these comments/questions are relevant to other
> developers...let's answer them, and I can help updating javadoc, etc
> once I'm sure I understand it]
>
> I'm still learning annotations, so I don't "get" the javadoc for
> @Extract and @Inject.
>
> Suggestion: there should be examples in the javadoc showing how to use
> the annotations.
>
> For example, the Javadoc
> (https://hk2.dev.java.net/nonav/auto-depends/apidocs/org/jvnet/hk2/annotations/Extract.html)
> doesn't tell me anything really about how to use @Extract
> ("Annotation marks instances of object which are labeled as exported
> by a component"):
>
> 1. Exported to where?
Exported to the component registry (a.k.a. Habitat in HK2).
> 2. Under what name?
Unless you specify a name in @Extract, it is an unnamed object.
> What is the naming convention?
Any string
> 3. What do I write to @Inject it? What happens if it's not yet available?
>
Let's take an example:

@Service public class BarImpl implements PostConstruct {
    @Extract BazImpl baz;
    public BarImpl() {System.out.println("BarImpl()");}
    public void postConstruct() {baz = new BazImpl();}
}

public class BazImpl {
    public BazImpl() { System.out.println("BazImpl()");}
}

@Service public class Foo implements ModuleStartup {
    @Inject Habitat habitat;
    @Inject BarImpl bar;

    public void setStartupContext(StartupContext context) {}

    public void run() {
        System.out.println(bar.baz);
        System.out.println(habitat.getComponent(BazImpl.class));
    }
}

When you run it using mvn hk2:run, you shall see something like this:
BarImpl()
BazImpl()
sahoo.hk2test4.BazImpl_at_b3319f
sahoo.hk2test4.BazImpl_at_b3319f

The point worth noting is that BazImpl() is called only once and
habitat.getComponent(BazImpl.class) returned the same instance as
pointed to by bar.baz.

Note that, we need not mark BazImpl as a @Service, although in many
cases it may itself be a service. I think there is some work to be in
HK2 about @Extract processing, as it currently only exports the object
under the type name of the implementation class (in this case
BazImpl.class).

Yes, we plan to add some examples to the documents soon.
Thanks,
Sahoo
> ---
> Lloyd L Chambers
> lloyd.chambers_at_sun.com <mailto:lloyd.chambers_at_sun.com>
> Sun Microsystems, Inc
>
>
>