Guice And Scala - Injection on Generics Dependencies

安稳与你 提交于 2019-11-30 09:03:44
David

You need a TypeLiteral binding like this:

bind(new TypeLiteral[Repository[Domain]] {})
 .annotatedWith(classOf[DomainDependency])
 .to(classOf[DomainRepository])
 .in(Scopes.SINGLETON)

TypeLiteral is a special class that allows you to specify a full parameterized type. Basically, you can't instantiate a class with a generic type parameter.

Also, take a look at this answer.

See "How to inject class with generic type?" in the Guice FAQ.

As David says, you need a TypeLiteral to bind a generic type (remember - generic types are erased to just the class, without the type parameter at run-time).

Another alternative is to something like my Scala Guice library to build the TypeLiterals needed by Guice from Scala's Manifests. If you mix in the ScalaModule trait, you would then be able to do something like:

bind[Repository[Domain]]
 .annotatedWith[DomainDependency]
 .to[DomainRepository]
 .in(Scopes.SINGLETON)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!