Dropwizard/Jersey/HK2 Scala 中的依赖注入

Dropwizard/Jersey/HK2 Dependency Injection in Scala

尝试创建自定义 @Context 我可以通过 Jersey 注入我的资源。

this question 中的 Java 对此进行了介绍。 我已经阅读了也在 Java 中的 docs covering this。 最后一些代码涵盖相同的 topic (doing this all through Dropwizard) in Github.

第一部分是创建工厂。

斯卡拉:

import org.glassfish.hk2.api.Factory
import javax.inject.Inject
import javax.ws.rs.container.ContainerRequestContext
import MyObj

class MyObjFactory @Inject()(ctr: ContainerRequestContext) extends Factory[MyObj] {
  private final val context: ContainerRequestContext = ctr

  override def provide(): MyObj = context.getProperty("myObj").asInstanceOf[MyObj]

  override def dispose(myObj: MyObj): Unit = { }
}

下一部分是注册工厂,我假设 classOf[T] 是等同于 Java 的 T.class

的适当 Scala
import org.glassfish.hk2.utilities.binding.AbstractBinder

environment.jersey.register(new AbstractBinder {
  override def configure(): Unit = {
    bindFactory(classOf[MyObjFactory])
        .to(classOf[MyObj])
        .proxy(true)
        .proxyForSameScope(false)
        .in(classOf[RequestScoped])
  }
})

最后应该是实际注入:

@Path("/")
class MyResource {
    @GET
    def get(@Context uriInfo: UriInfo, @Context myObjFactory: MyObjFactory) = {
        // do stuff
    }
}

这一切都编译但在运行时失败,出现以下异常

ERROR [2017-04-05 00:26:14,605] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 8e5877857c823fef
! java.lang.IllegalArgumentException: Invalid injectee with required type of null passed to getInjecteeDescriptor
! ... 87 common frames omitted
! Causing: org.glassfish.hk2.api.MultiException: A MultiException has 1 exceptions.  They are:
! 1. java.lang.IllegalArgumentException: Invalid injectee with required type of null passed to getInjecteeDescriptor
! 
! at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetInjecteeDescriptor(ServiceLocatorImpl.java:545)
! at org.jvnet.hk2.internal.ServiceLocatorImpl.getInjecteeDescriptor(ServiceLocatorImpl.java:584)
! at org.glassfish.jersey.internal.inject.ContextInjectionResolver.compute(ContextInjectionResolver.java:102)
! at org.glassfish.jersey.internal.inject.ContextInjectionResolver.compute(ContextInjectionResolver.java:98)
! at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.call(Cache.java:97)

无法判断是我在转换为 Scala 时犯了错误,还是我在实际注册 Binder 时做错了什么。

get(@Context uriInfo: UriInfo, @Context myObjFactory: MyObjFactory) <===

您正在尝试注入 FactoryFactory 用于创建 服务。在这种情况下,它并不意味着要被注入。你要注入的是实际的服务,后面会用到工厂来创建

get(@Context uriInfo: UriInfo, @Context myOb: MyObj) <===