Guice运行时依赖项参数重新注入

pfh:

关于Guice的问题。我仍在学习,但我可以理解基本原理。

这个问题已经在网上被问过几次了,但是从来没有一个具体的答案(我找不到)。

假设我遇到图片上的情况(网上有个类似的例子)。

在此处输入图片说明

public class Dog {}

public class Walk implements Walkable {
    private final Dog dog;
    private final boolean leash;

    @Inject
    public Walk(Dog dog, @Assisted boolean leash) {
        this.dog = dog;
        this.leash = leash;
    }

    public void go() {
    }
}

public interface Walkable {
    void go();
}

public interface WalkFactory {
    Walk create(boolean leash);
}

public class AssistedMain {
    public static void main(String[] args) {
        Injector i = Guice.createInjector(new AbstractModule() {
            protected void configure() {

                install(new FactoryModuleBuilder().
                        implement(Walkable.class, Walk.class).
                        build(WalkFactory.class));
            }
        });

        Walk walk = i.getInstance(WalkFactory.class).create(true);
    }
}

太好了 但是问题是-我可以以某种方式将该对象实例重新注入到“容器”(注入器)中,以便在依赖于此依赖项的类上使用。

因此,让我们添加interface Personclass PersonImpl

在此处输入图片说明

新的类来源是:

public interface Person {
    void walkDog();
}

public class PersonImpl implements Person {
    private Walkable walkable;

    @Inject
    public PersonImpl(Walkable walkable) {
        this.walkable = walkable;
    }

    public void setWalkable(Walkable walkable) {
        this.walkable = walkable;
    }

    public void walkDog() {
        walkable.go();
    }
}

因此,问题是-我是否能够以某种方式将该特定实例注入添加的对象中。这是一个简单的示例,但是我们可以假定该级别之下有10个级别的类。

我发现的解决方案不是很灵活。就像是:

Injector i = Guice.createInjector(new SimpleModule(false, dog));

然后绑定到具体实例。这不是很动态。基本上,每次我需要不同的运行时/动态参数时,都必须重新创建注射器。

Provider<T>是不错的FactoryModuleBuilder帮助,但我怎么能注入的对象回来?

是否有针对此问题的更多动态解决方案?

谢谢。

pfh:

MPierce-同意。虐待尝试解释我可视化问题的方式(如果我错了,可以纠正我)。

可以说,它比服务更能管理的想法是源于“服务定位器”模式的原始想法。

我们可以将应用程序划分为Service和Data类,或者您可以说我们拥有应用程序和基础结构代码 -很好的书“ Dependency Injection”。

因此,从根本上讲,依赖注入和依赖注入框架通常都很棒。用于解决基础结构或“服务”代码。

基本上,任何注入到Container / Injector中的动态(运行时)参数都将迫使您结束对象图

例如,我们有以下设计:

在此处输入图片说明

EmailMessage is a runtime parameter. It can be "injected" into email service outside the Container/Injector, but it ends the object graph. If we want to request EmailDispatcher, after we injected the EmailMessage into EmailService(which is, I repeat, done outside injector), we could no longer fetch EmailDispatcher from the injector.

Then, you could redesign your model so it "fits" into the Container/Injector concept of dynamic parameters.

在此处输入图片说明

But then again, you forced the design, and suddenly, EmailDispatcher has too many responsibilites. It could be used in such a context, where you dont have many infrastructure classes.

在此处输入图片说明

而且,当您具有如第三张示例图中所示的设计时,就不能使用Injector / Container来获取NextService3实例(也不能低于EmailDispatcher的级别)。

问题是- 如果您有任何动态(运行时)参数,则只能对需要动态参数的类之上的类使用依赖项注入,而您会忘记下面的类。

ew

正确?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章