2017-04-05 56 views
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) 

不能告诉。

回答

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

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

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

良好的通话,但仍然有运行时错误失败 - 我已经更新,以反映您的建议。 – diplosaurus

+0

其实我只是删除了'.proxy(true)'和'.proxyForSameScope(false')方法,并且一切正常。不知道这些是否重要,但是我很感谢你的帮助! – diplosaurus

+1

很高兴你的工作。如果你想在你的文章中添加新的内容,那么就这样做,_add_ it,不要放弃之前的内容,只需要放一些“编辑“在底部,然后在下面添加新的内容 –