简体   繁体   English

构造函数vs字段与方法注入Dagger 2

[英]Constructor vs Field vs Method Injection Dagger 2

I have been learning Dagger 2 for a week and in the tutorials I read, most of them wrote that it is preferable to use Constructor injection over Field and Method injection. 我已经学习了Dagger 2一周,在我读过的教程中,大多数人写道,最好在Field和Method注入时使用Constructor注入。

I am confused and wanted to make clear, when should I be using Constructor injection, and when Field and Method injection. 我很困惑并希望明确,何时应该使用Constructor注入,以及Field和Method注入时。 Thanks in advance. 提前致谢。

I can't say this is the definite answer, but I'd like to share my opinion. 我不能说这是明确的答案,但我想分享我的看法。 I prefer constructor injection because you're forced to create the object by fulfilling its dependencies. 我更喜欢构造函数注入,因为您必须通过实现其依赖项来创建对象。 In other words you'll never end up in the situation that you call an object's method and because some dependency wasn't set, you get a null pointer exception (unless you set it as null on purpose in which case you're asking for it). 换句话说,你永远不会在你调用对象的方法的情况下结束,并且因为没有设置某个依赖项,你会得到一个空指针异常(除非你故意将它设置为null ,在这种情况下你要求的是它)。 I tend to always use constructor dependency injection everywhere. 我倾向于始终在任何地方使用构造函数依赖注入。

That said, sometimes it's simply not possible. 也就是说,有时候根本不可能。 In Android for example the Activities are created by the system and hence we don't usually have our own constructor to call and pass in the dependencies. 例如,在Android中,活动是由系统创建的,因此我们通常没有自己的构造函数来调用和传递依赖项。 Here I often use field dependency injection. 在这里,我经常使用字段依赖注入。 I do this because there's a lot of tools out there that help you out with this. 我这样做是因为有很多工具可以帮助你解决这个问题。

A third options is through setters . 第三种选择是通过setters Personally I never used it. 我个人从来没用过它。 Not entirely sure where this would be needed. 不完全确定需要什么。 Perhaps when the dependency has to change at run time? 也许什么时候依赖必须在运行时改变? Not sure. 不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM