gpt4 book ai didi

java - 使用 Guice 为可重用组件注入(inject)不同的实例

转载 作者:行者123 更新时间:2023-11-29 04:33:06 24 4
gpt4 key购买 nike

我是依赖注入(inject)新手,我正在尝试使用 Google Guice 解决以下问题:

在 Web 应用程序中,我有一些选项卡需要多次重复使用,但每次都对其 UI 组件和模型有不同的依赖性。类似于这里的代码:

class MenuTabView
{
private MenuTab fooTab;
private MenuTab barTab;
}

class MenuTab
{
private UiComponent component;

@Inject
public MenuTab(UiComponent component)
{
this.component = component;
}
}

class UiComponent
{
private Model model;

@Inject
public UiComponent(Model model)
{
this.model = model;
}
}

class FooComponent extends UIComponent {}
class BarComponent extends UIComponent {}

class FooModel implements Model {}
class BarModel implements Model {}

如何将 FooModel 和 FooComponent 注入(inject) fooTab和 BarModel 和 BarCompoment 到 barTab?

我已经阅读了很多有关 Google Guice 中可用的不同技术的文章,但没有一种技术能够解决这个问题,在我天真的眼中,这应该是一个简单的问题。我试过给 fooTab 和 barTab 绑定(bind)注释,但它们只有在我注入(inject)选项卡而不是选项卡的依赖项时才有效。解决这个问题最方便的方法是什么?

最佳答案

这对我来说听起来像是常见的“机器人腿”问题……FAQ 中对此进行了介绍并且可以通过使用私有(private)模块来解决:

class LegModule extends PrivateModule {
private final Class<? extends Annotation> annotation;

LegModule(Class<? extends Annotation> annotation) {
this.annotation = annotation;
}

@Override
protected void configure() {
bind(Leg.class).annotatedWith(annotation).to(Leg.class);
expose(Leg.class).annotatedWith(annotation);

bindFoot();
}

abstract void bindFoot();
}

public static void main(String[] args) {
Injector injector = Guice.createInjector(
new LegModule(Left.class) {
@Override void bindFoot() {
bind(Foot.class).toInstance(new Foot("leftie"));
}
},
new LegModule(Right.class) {
@Override void bindFoot() {
bind(Foot.class).toInstance(new Foot("righty"));
}
});
}

关于java - 使用 Guice 为可重用组件注入(inject)不同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com