Roboguice @Inject 服务混乱
private Service service;
@Inject
public ClassName(final Service service) {
this.service = service;
}
@Inject
private Service service;
有人可以告诉我这两种注射方式之间的区别吗?
private Service service;
@Inject
public ClassName(final Service service) {
this.service = service;
}
@Inject
private Service service;
Could someone please tell me the difference between this 2 styles of injection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个表示注入器将调用您的构造函数并提供适当的 Service 对象。您在构造函数中做什么取决于您。
第二个说它将适当地设置你的成员变量(这意味着你可以有一个默认的构造函数,并且它仍然会神奇地为你设置变量)。
一般来说,我更喜欢第一个,因为它使您的依赖关系保持明确,但我确信使用方法 2 有充分的理由。
我没有使用 RoboGuice,但我认为它与常规 Guice 具有相同的一般原则 - 以及一些相关的@Inject 的文档位于其 wiki:http://code.google.com/p/google-guice/wiki/Injections
The first one says that the injector will call your constructor and provide the appropriate Service object. What you do in the constructor is up to you.
The second one says that it will set your member variable appropriately (meaning you could have a default constructor, and it would still magically set the variable for you).
Generally, I prefer the first, as it keeps your dependencies explicit, but I am sure there are good reasons for using method 2.
I haven't used RoboGuice, but I assume it has the same general principles as regular Guice - and some relevant @Inject documentation for that is at their wiki: http://code.google.com/p/google-guice/wiki/Injections