HK2 IterableProvider named method not finding Implementation

别来无恙 提交于 2019-11-29 16:58:09

Yeah so I'm not sure why it doesn't work with the @Named annotation value, as that's what's stated int the javadoc, but without the need for any annotations, we can configure the name when we do our bindings. We can do so with the named method.

register(new AbstractBinder(){
    @Override
    public void configure() {
        bind(Foo1Impl.class).named("foo1").to(Foo.class);
        bind(Foo2Impl.class).named("foo2").to(Foo.class);
    }
});

UPDATE

So the above solution has been tested. If you are having problems still, post a complete runnable example that demonstrates it not working, like below (which is working)

Interface and Implementations

public interface Greeter {
    String getGreeting(String name);
}

public class EnglishGreeter implements Greeter {
    @Override
    public String getGreeting(String name) {
        return "Hello " + name + "!";
    }
}

public class SpanishGreeter implements Greeter {
    @Override
    public String getGreeting(String name) {
        return "Hola " + name + "!";
    }
}

Resource

@Path("greeting")
public class GreetingResource {

    @Inject
    private IterableProvider<Greeter> greeters;

    @GET
    public Response getResponse(@QueryParam("lang") String lang,
                                @QueryParam("name") String name) throws Exception {

        Greeter greeter = greeters.named(lang).get();
        String message = greeter.getGreeting(name);
        return Response.ok(message).build();
    }
}

Binding. I did it in a Feature, but in a ResourceConfig, it's all the same.

@Provider
public class GreetingFeature implements Feature {
    @Override
    public boolean configure(FeatureContext context) {
        context.register(new AbstractBinder(){
            @Override
            public void configure() {
                bind(EnglishGreeter.class).named("english")
                        .to(Greeter.class).in(Singleton.class);
                bind(SpanishGreeter.class).named("spanish")
                        .to(Greeter.class).in(Singleton.class);
            }
        });
        return true;
    }  
}

Result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!