5

In HK2 the basic example code for configuring injection is this (within a class that extends AbstractBinder:

bind(BuilderHelper
    .link(FooImpl.class)    // the class of the object to be injected
    .to(FooInterface.class) // identifies what @Inject fields to link to
    .build());

This causes HK2 to call the constructor FooImpl() when it needs to create a FooInterface.

What if FooImpl doesn't have a constructor?

  • What if it's intended to be instantiated with a static factory method FooImpl.getInstance()
  • What if it's intented to be instantiated by a factory object fooFactory.create()

I see that ResourceConfig has a method bind(FactoryDescriptors factoryDescriptors) but it is not clear to me what the idiom is for building a FactoryDescriptors object, and have not been able to find any examples online.

slim
  • 40,215
  • 13
  • 94
  • 127

2 Answers2

8

While I still can't see a way to do it using the BuilderHelper EDSL (it appears this is overkill for the common case too), the following works:

  bindFactory(FooFactory.class)
       .to(FooInterface.class);

This requires that FooFactory is an implementation of Factory<FooInterface>, so you need a facade around any existing factory you have. I did it as a private inner class where I needed it.

 private static class FooFactory implements Factory<FooInterface> {

    @Override
    public void dispose(FooInterface foo) {
      // meh
    }

    @Override
    public FooInterface provide() {
      return SomeFactory.getInstance();
    }
 }
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
slim
  • 40,215
  • 13
  • 94
  • 127
4

Currently hk2 only supports the Factory interface for creating objects with special constructor needs. We have been considering adding a static method constructor or doing some sort of CDI @Produces type of mechanism. It is difficult to decide which of these things is worth the extra complexity (we try very hard to stay light-weight).

I think in your code example above your private static class needs to implement the Factory interface, right?

jwells131313
  • 2,364
  • 1
  • 16
  • 26
  • FWIW I think it's fine how it is, but the HK2 documentation needs some examples of it in use. – slim Dec 05 '13 at 11:55
  • 2
    I have added this bug https://java.net/jira/browse/HK2-167 to track adding more examples concerning factories. Other people have had problems using the EDSL with factories as well, so I think it is a common problem – jwells131313 Dec 05 '13 at 12:11