尝试创建自定义@Context
我可以通过Jersey注入我的资源。
这在this question中的Java中有所介绍。 我已经阅读了同样使用Java的docs covering this。 最后一些代码覆盖了相同的topic (doing this all through Dropwizard) in Github。
第一部分是创建工厂。
Scala的:
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
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$1.compute(ContextInjectionResolver.java:102)
! at org.glassfish.jersey.internal.inject.ContextInjectionResolver$1.compute(ContextInjectionResolver.java:98)
! at org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
无法判断我是否在转换为Scala时犯了错误,或者我在注册Binder时遇到了错误。
答案 0 :(得分:2)
get(@Context uriInfo: UriInfo, @Context myObjFactory: MyObjFactory) <===
您正在尝试注入Factory
。 Factory
用于创建服务。在这种情况下不打算注入。您要注入的是实际服务,工厂将用于在场景后面创建它
get(@Context uriInfo: UriInfo, @Context myOb: MyObj) <===