Spring.NET如何使用私有setter?
在尝试 这个关于 Spring.NET 中集合的问题时,我发现 Spring 可以使用私有 setter 注入依赖项。 我有两个问题:
- 这是否记录在任何地方?
- 是否建议使用私人设置器?
文档说:
基于 Setter 的 DI 是通过在对象上调用 setter 方法来实现的...
当然,它没有明确指出公共 setter 方法,但这就是我一直假设的。 我在 .NET 3.5 上使用版本 1.0.2。
While experimenting with this question on collections in Spring.NET, I discovered that Spring can inject a dependency using a private setter. I have two questions:
- Is this documented anywhere?
- Is using private setters recommended?
The documentation says:
Setter-based DI is realized by calling setter methods on your objects...
Granted, it doesn't explicitly say public setter methods, but that's what I had always assumed. I'm using version 1.0.2 on .NET 3.5.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
唐,
不,这没有记录下来 - 主要是因为我们不推荐它。 该功能是为了在处理遗留/第三方库时支持罕见的极端情况。
您应该只使用公共设置器,您也可以从单元测试中调用它们!
哈,
埃里希
Don,
no this is not documented asfaik - mostly because we don't recommend it. The feature is there to support rare cornercases when dealing with legacy/3rd party libraries.
You should only use public setters that you may also call from within your unit tests!
hth,
Erich
Spring 的 Java 版本使用反射,它可以获取那些私有 setter。 这很好,因为您不想强迫某人仅仅为了满足 Spring 的要求而改变一个不可变的对象。
就我个人而言,我更喜欢尽可能使用构造函数注入。
The Java version of Spring uses reflection, which can get at those private setters. That's good, because you wouldn't want to force someone to change an immutable object just to satisfy Spring.
Personally, I prefer using constructor injection whenever I can.