0

我正在尝试将具有运行时变量的对象传递给另一个对象。如何使用 Guice 实现这一目标?我是依赖注入的新手。

我想创建几个 A 对象(它们的数量在运行时决定)以及使用 A 对象的许多 B 对象。但首先让我们从他们两个中的一个对象开始。

感谢您的帮助。

public interface IA {
    String getName();
}

public class A implements IA {
    @Getter
    protected final String name;

    @AssistedInject
    A(@Assisted String name) {
        this.name = name;
    }
}

public interface IAFactory {
    IA create(String name);
}

public interface IB {
    IA getA();
}

public class B implements IB {  
    @Getter
    protected final IA a;

    //...
    // some more methods and fields
    //...

    @Inject
    B(IA a) {
        this.a = a;
    }
}

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        install(new FactoryModuleBuilder()
         .implement(IA.class, A.class)
         .build(IAFactory.class));

        bind(IB.class).to(B.class);
    }
}

public class Main() {
    public static void main(String[] args) throws Exception {
        if(args.size < 1) {
            throw new IllegalArgumentException("First arg is required");
        }
        String name = args[0];

        Injector injector = Guice.createInjector(new MyModule());
        IB b = injector.getInstance(IB.class);
        System.out.println(b.getA().getName());
    }
}
4

1 回答 1

0

我认为您对此并不完全清楚。所以让我稍微解释一下。

首先,您创建了一个工厂,您将使用它来创建A. 您这样做是因为 Guice 不知道 parameter 的值name

现在你想要的是创建一个B依赖于A. 您要求 Guice 给您一个实例,B但 Guice 将如何创建一个B没有 的实例A?您还没有绑定任何A.

因此,要解决此问题,您要么必须B手动创建一个实例。

您可以通过以下方式实现它。

首先,你需要一个工厂B

public interface IBFactory {
    IB create(String name);
}

然后你需要在你的类中进行以下更改B

public class B implements IB {  

    protected final A a;

    @AssistedInject
    public B(@Assisted String name, IAFactory iaFactory) {
        this.a = iaFactory.create(name);
    }
}

现在在你的main方法中

public static void main(String[] args) throws Exception {
    if(args.size < 1) {
        throw new IllegalArgumentException("First arg is required");
    }
    String name = args[0];

    Injector injector = Guice.createInjector(new MyModule());
    IBFactory ibFactory = injector.getInstance(IBFactory.class);
    IB b = ibFactory.create(name)
    System.out.println(b.getA().getName());
}

另外,不要忘记更新您的配置方法并安装 B 工厂。

protected void configure() {
    install(new FactoryModuleBuilder()
     .implement(IA.class, A.class)
     .build(IAFactory.class));

    install(new FactoryModuleBuilder()
     .implement(IB.class, B.class)
     .build(IBFactory.class));
}

注意 我正在传递nameB 类。您可以更新 IBFactory 以IA作为辅助参数,然后首先IA使用外部创建一个实例IAFactory并将实例传递IA给以IBFactory创建一个实例IB

于 2019-08-13T16:03:09.427 回答