1
試圖創建自定義@Context
我可以通過Jersey注入到我的資源中。Scala中的Dropwizard/Jersey/HK2依賴注入
這在Java中被覆蓋在this question。 我讀過docs covering this這也是在Java中。 最後一些代碼覆蓋了相同的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
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
}
}
This all com樁但在運行時失敗,出現以下異常,如果我犯了一個錯誤與我轉換爲斯卡拉或我做錯了什麼實際註冊的活頁夾
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)
不能告訴。
良好的通話,但仍然有運行時錯誤失敗 - 我已經更新,以反映您的建議。 – diplosaurus
其實我只是刪除了'.proxy(true)'和'.proxyForSameScope(false')方法,並且一切正常。不知道這些是否重要,但是我很感謝你的幫助! – diplosaurus
很高興你的工作。如果你想在你的文章中添加新的內容,那麼就這樣做,_add_ it,不要放棄之前的內容,只需要放一些「編輯「在底部,然後在下面添加新的內容 –