On May 22, 2013, at 5:03 PM, Paulo Pires <pjpires_at_gmail.com> wrote:
> +1
>
> On Sat, May 11, 2013 at 9:13 PM, algermissen1971 <algermissen1971_at_mac.com> wrote:
> Hi Jersey2 devs,
>
> can anyone help shed some light on how to implement custom providers for Jersey 2?
Jersey 2.0 uses HK2 for injection. So what you need to do is to provide an implementation of a HK2 Binder that defines how the injection should be satisfied - very similar to the way Guice works. See e.g.:
https://github.com/jersey/jersey/blob/master/ext/mvc/src/main/java/org/glassfish/jersey/server/mvc/internal/MvcBinder.java
Then you need to register your binder in your ResourceConfig as you would register a resource or any other JAX-RS/Jersey provider.
>
> I saw some discussions on this for Jersey 1, but the classes mentioned there did not survive the migration to Jersey 2. Any hints or material how to approach custom injection in Jersey 2?
>
> Specifically, I need to get hold of a managed object (say, a service that I can use to look up credentials given a loginId) and pass that to a new filter instance during runtime setup:
>
> So far, I am doing something like the following:
>
> @javax.ws.rs.ApplicationPath("r")
> public class ApplicationConfig extends ResourceConfig {
>
> MyCredentialsService s; // ............. this needs to be injected
Use standard JSR330 @Inject.
>
> public ApplicationConfig() {
>
> packages( ... bunch of packages with resource classes ...);
> this.registerInstances(new SpecialAuthFeature(s)); // ............ pass injected service
> }
> }
>
> Now, I understand (I hope) that I could do this with CDI, using the provided Binder mechanisms.
It's not CDI, it's HK2. But the fact is that you CAN use CDI to define injection bindings that should work with @Inject too.
> However, I want at least my filters to steer clear of jersey dependencies. Instead, I thought I could simply pass the injected object to the filter constructor.
You can use @Inject in your filters too. That should work both with CDI and HK2 defined bindings.
>
> But how do I get the service injected into the constructor of my ResourceConfig?
:) Use @Inject on your constructor.
Marek
>
> Jan
>
>
>
> --
> Paulo Pires