Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to create a class whose objects can be injected using the @Context annotation (or better yet a custom annotation for cases where I need to pass an argument to the annotation) into resource methods. In Jersey 1.* I would have used InjectableProvider (in my case together with AbstractHttpContextInjectable). What I'm trying to achieve is something like @Auth [1] from dropwizard (which uses Jersey 1.7).

The injection capabilities of Jersey were replaced by HK2 as far as I know and I could not find any example of what I'm describing.

Edit: See this question for further problems I have encountered while trying to follow Michal's guide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
108 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to implement InjectionResolver<T> interface from HK2. Take a look at existing implementations that are present in Jersey workspace:

Once you have this, you need to extend AbstractBinder from HK2 and bind your InjectionResolver via it's #configure() method:

public class MyResolverBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bind(MyInjectionResolver.class)
                .to(new TypeLiteral<InjectionResolver<MyAnnotation>>() {})
                .in(Singleton.class);
    }
}

... and register an instance of this binder in your application class (or via feature):

Feature:

public class MyFeature implements Feature {

    @Override
    public boolean configure(final FeatureContext context) {
        context.register(new MyResolverBinder());
        return true;
    }
}

register MyFeature into Application:

public class JaxRsApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final HashSet<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(MyFeature.class);
        // Register other providers or resources.
        return classes;
    }
}

register MyResolverBinder or Feature in the ResourceConfig

new ResourceConfig()
        // Register either MyFeature
        .register(MyFeature.class)
        // or MyResolverBinder
        .register(new MyResolverBinder())
        // Register other providers or resources
        .packages("my.package");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...