gpt4 book ai didi

java - 如何在 Google Guice 中创建实现实例

转载 作者:行者123 更新时间:2023-12-02 05:32:50 25 4
gpt4 key购买 nike

我是 Google Guice 新手,需要一些帮助。我创建了一个这样的模块:

public interface Foo {
Bar doSomething();
}

public class MyFoo implements Foo {
Bar doSomething() {
// create an instance of MyBar
}
}

public interface Bar {
void run();
}

public interface MyBar implements Bar {
void run();
}

public class MyModule extends AbstractModule {

@Override
protected void configure() {
bind(Foo.class).to(MyFoo.class);
}
}

我的问题是:在“MyFoo”类中创建 MyBar 实例的正确方法是什么?这样做感觉不对:

public class MyFoo implements Foo {
Bar doSomething() {
MyBar mybar = new MyBar();
return mybar;
}
}

当我需要时,有没有办法通过 MyModule 注入(inject)一个新的 MyBar 实例,或者我是否必须在 MyBar 的构造函数中注入(inject)一个工厂来创建 MyBar 实例?如果我必须使用工厂,我可以控制通过模块生成哪个实现吗?

最佳答案

也许您正在寻找提供商?提供者或多或少是工厂,是 Guice API 的一部分,因此您不必实现它们。

public class MyFoo implements Foo {
@Inject Provider<MyBar> myBarProvider;

Bar doSomething() {
return myBarProvider.get(); // returns a new instance of MyBar
}
}

详情参见 https://github.com/google/guice/wiki/InjectingProviders

关于java - 如何在 Google Guice 中创建实现实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514737/

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