9

How do I inject a constant into some class using HK2 in jersey? With Guice I could have some class like

public class DependsOnFoo {

    @Inject
    public DependsOnFoo(@Named("FOO") String foo) {
        ...
    }
    ...
}

and I would configure it in the injector with something like

bind(String.class).named("FOO").toInstance(new String("foo"))

What's the equivalent, if any, in HK2?

agnul
  • 12,608
  • 14
  • 63
  • 85

1 Answers1

21

I'm in the process of learning hk2 coming from Guice. Honestly I am still in the weeds a little with the complexity of hk2 vs the simplicity of guice. I did find this solution to work for me and it is much similar to the Guice builder. This did seem a little more straight forward than having to use the ServiceLocatorUtilitiesclass.

public class IOCMockRestModule extends AbstractBinder
    bind(20000).to(Integer.class).named("MAX_REQUEST_TIMEOUT");
}

And to use the injected value:

@Inject
protected CustomerResource(ICustomerProvider customerProvider, @Named("MAX_REQUEST_TIMEOUT") int maxTimeoutMillis) {
Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
Chris Hinshaw
  • 6,967
  • 2
  • 39
  • 65
  • 2
    Is it possible to implement this in a more flexible way that doesn't require a new `bind()` for each new named value such as `MAX_REQUEST_TIMEOUT`? I'm hoping something more flexible is possible where the named value can be read at runtime and looked via custom implementation such as from a properties file, environment variable, etc? – hayduke Oct 17 '17 at 01:07
  • 1
    I don't think hk2 has this functionality but you could look at guice's com.google.inject.name.Names.bindProperties(Binder binder, Properties properties) as a guide to create your own. It should be pretty straight forward I think to port this functionality to hk2. – Chris Hinshaw Oct 17 '17 at 16:06
  • That's helpful thanks @Chris. Since I wanted to stick to HK2 and not introduce another technology I ended up successfully using a custom annotation and InjectionResolver to get the behavior I wanted as described here https://stackoverflow.com/a/41436316/5661065 – hayduke Oct 17 '17 at 21:54