如何让泽西与Dagger依赖注入一起工作?

Rin*_*nke 19 java dependency-injection jersey jsr330 dagger-2

Jersey通常使用HK2依赖注入,但我想使用Jersey和Dagger 2.Dagger和HK2都实现了JSR 330,我已经把它作为证据证明这应该是可能的而不需要太多努力.我找到了使泽西与CDI(例如Weld),Spring DI和Guice合作的方法,但我在Dagger上找不到任何东西.

提供一些上下文:我在SE环境中运行Grizzly-Jersey服务器,而不是在EE容器中运行.我的Maven项目有com.google.dagger:daggerorg.glassfish.jersey.containers:jersey-container-grizzly2-http依赖,但不是 org.glassfish.jersey.inject:jersey-hk2,因为我想用Dagger取代HK2.

资源类看起来像这样:

@Path("/example")
public final class ExampleResource {

    private final Dependency dependency;

    @Inject
    public ExampleResource(final Dependency dependency) {
        this.dependency = Objects.requireNonNull(dependency);
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Example getExample() {
        return this.dependency.giveExample();
    }

}
Run Code Online (Sandbox Code Playgroud)

并且Dagger组件可以例如定义如下:

@Component
public interface Application {

    public ExampleResource exampleEndpoint();
    public XyzResource xyzEndpoint();
    // etc.

}
Run Code Online (Sandbox Code Playgroud)

这样主要方法看起来类似于:

public final class Main {

    public static void main(final String[] args) {
        final Application application = DaggerApplication.create();
        final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(80).build();
        final ResourceConfig resourceConfig = new ResourceConfig();
        // how to initialize `resourceConfig` using `application`?
        final HttpServer httpServer = GrizzlyHttpServerFactory
                .createHttpServer(baseUri, resourceConfig, false);
        try {
            httpServer.start();
        } catch (final IOException ex) {
            ...
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

立即运行应用程序会导致异常:IllegalStateException: InjectionManagerFactory not found.似乎需要此工厂的Dagger实现.

我的问题是:如何将Dagger与泽西相结合?

小智 0

您需要实现一个InjectionManagerFactoryInjectionManager委托返回给 Dagger 的方法,并通过在 中放入一个条目将其注册为一项服务META-INF/services,类似于此处的 hk2: https: //github.com/jersey/jersey/blob/master/inject/ hk2/src/main/resources/META-INF/services/org.glassfish.jersey.internal.inject.InjectionManagerFactory 但引用您自己的实现。