加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何避免Scala中的依赖注入?

发布时间:2020-12-16 10:07:43 所属栏目:安全 来源:网络整理
导读:我读了 Dependency Injection Without the Gymnastics PDF,这表明不需要任何花哨的DI框架,但它超出了我的掌握(至少没有具体的例子).当我有机会的时候,我会尝试观看 Dependency Injection Without the Gymnastics和 Dead Simple Dependency Injection. 在Java
我读了 Dependency Injection Without the Gymnastics PDF,这表明不需要任何花哨的DI框架,但它超出了我的掌握(至少没有具体的例子).当我有机会的时候,我会尝试观看 Dependency Injection Without the Gymnastics和 Dead Simple Dependency Injection.

在Java中使用Guice,如果A依赖于B和C并且B和C都依赖于D,那么就会有:

public class A {
    @Inject
    public A(B b,C c) {
        this.b = b;
        this.c = c;
    }
}

public class B {
    @Inject
    public B(D d) {
        this.d = d;
    }
}

public class C {
    @Inject
    public C(D d) {
        this.d = d;
    }
}

public class D { /* ... */ }

以及一个模块,说明要使用哪个D实现,然后只需要从进样器中请求A的实例:

A a = injector.createInstance(A.class);

鉴于上面的URL中显示的内容,上述代码的Scala等价物如何?

FWIW,我也正在调查https://github.com/dickwall/subcut/blob/master/GettingStarted.md,我只是想了解反DI解决方案.

解决方法

对于您正在描述的用例,隐式参数完全足够.

case class A(implicit b: B,c: C)
case class B(implicit d: D)
case class C(implicit d: D)
class D { /* ... */ }

implicit val theD = new D
implicit val theB = B()
implicit val theC = C()

现在你可以通过以下方式要求A:

val a = A()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读