使用Guice注入通用实现

编程入门 行业动态 更新时间:2024-10-08 02:19:58
本文介绍了使用Guice注入通用实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够使用Guice注入通用接口的通用实现。

I would like to be able to inject a generic implementation of a generic interface using Guice.

public interface Repository<T> { void save(T item); T get(int id); } public MyRepository<T> implements Repository<T> { @Override public void save(T item) { // do saving return item; } @Override public T get(int id) { // get item and return } }

在使用Castle.Windsor的C#中,我能够要做的事情:

In C# using Castle.Windsor, I'd be able to do:

Component.For(typeof(Repository<>)).ImplementedBy(typeof(MyRepository<>))

但是我不要认为Guice中存在等价物。我知道我可以在Guice中使用 TypeLiteral 来注册个别实现,但有没有办法像Windsor那样一次注册它们?

but I don't think the equivalent exists in Guice. I know I can use TypeLiteral in Guice to register individual implementations, but is there any way to register them all at once like in Windsor?

修改:

以下是使用示例:

Injector injector = Guice.createInjector(new MyModule()); Repository<Class1> repo1 = injector.getInstance(new Key<Repository<Class1>>() {}); Repository<Class2> repo2 = injector.getInstance(new Key<Repository<Class2>>() {});

虽然更有可能注入另一个类:

Although the more likely usage would be injection into another class:

public class ClassThatUsesRepository { private Repository<Class1> repository; @Inject public ClassThatUsesRepository(Repository<Class1> repository) { this.repository = repository; } }

推荐答案

In为了在Geice中使用泛型,你需要使用 TypeLiteral 类绑定泛型变体。这是一个Guice注入器配置如下所示的示例:

In order to use generics with Guice you need to use the TypeLiteral class to bind the generic variants. This is an example of how you're Guice injector configuration could look like:

package your-application; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; public class MyModule extends AbstractModule { @Override protected void configure() { bind(new TypeLiteral<Repository<Class1>>(){}) .to(new TypeLiteral<MyRepository<Class1>>(){}); } }

(存储库是通用接口,MyRepository是通用实现,Class1是泛型中使用的特定类。

更多推荐

使用Guice注入通用实现

本文发布于:2023-11-25 21:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Guice

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!