java - Guice 中构造函数修饰符的最佳实践

标签 java dependency-injection guice

现在,我正在阅读Guice's official document.他们说

As a correction, simply limit the visibility of both your implementation classes, and their constructors. Typically package private is preferred for both, as this facilitates:

binding the class within a Module in the same package

unit testing the class through means of direct instantiation

As a simple, mnemonic remember that public and @Inject are like Elves and Dwarfs: they can work together, but in an ideal world, they would coexist independently.

通过阅读文档,我知道公共(public)构造函数有多么危险。 引用的句子似乎是解决方案,但我不确定确切的含义。 那么,您可以检查一下我的想法是否正确。

首先,他们说将类绑定(bind)在同一包的模块中。 这意味着例如您的系统中有一个包。而且使用与包对应的Module好不好?那么,基本上你有相同数量的模块和相同数量的包?

其次,您可以看到通过直接实例化的方式对类进行单元测试。 这意味着我们应该使用直接实例化来对类进行单元测试,而不是 GuiceModule? 我认为 Guice 对于测试也很有用,尤其是正如他们所说的单元测试。

我有点困惑,谁能帮我解释一下吗?

最佳答案

First, they say binding the class within a Module in the same package. This means for example you have a package in a system. And it is good to use a Module corresponding with the package? So, basically you have the same number of Modules and same number of packages?

是的。无论如何,你应该始终使用包。除了玩具大小的程序之外,不鼓励使用默认包。

我通常希望有一个 org.whatever.foo.some.feature 包,其中包含一个名为 FeatureModule 的模块类(即包的名称 + 模块,而不是特定的FeatureModule)。

Second, you can see unit testing the class through means of direct instantiation. This means we should do unit testing a class using direct instantiation, not Guice's Module? I think Guice is also useful for a testing, especially unit testing as they said.

如果直接注入(inject)要测试的内容,就更容易准确地看到正在测试的内容。

当然,您可以使用 guice,但是绑定(bind)存在一定量的“魔法发生在这里”,这可能会隐藏测试中的意外行为。

这适用于单元测试;如果您正在进行集成测试,您可能确实希望使用类似于生产代码的方式,这可能涉及 guice。

关于java - Guice 中构造函数修饰符的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221990/

相关文章:

java - 关于从 HTML 中的复选框值更新 MySql 数据库的建议

c# - 有人可以解释 Microsoft Unity 吗?

java - Jersey 的依赖注入(inject)

java - 如何验证 Guice 作用域在测试中的使用情况?

吉斯 : Is it possible to get all binded instances given a particular parent/interface/annotation?

java - solr dismax 短语搜索

java - Guava 中 Supplier<T> 的倒数

java - freemarkers 跳过 assertNotNull InvalidReferenceException

asp.net-mvc-3 - 带有 MVC 和自定义 MembershipProvider 的 DI

java - 让每个具体类都从接口(interface)继承是错误的吗?