为什么Spring.Net在解析配置时实例化对象?
我有一个 SimpleObject
类
public class SimpleObject
{
public SimpleObject()
{
Console.WriteLine("Instantiated");
}
}
和一个简单的 Spring 配置:
<object id="simpleObject" type="SpringTest.SimpleObject, SpringTest" />
当我解析配置以获取上下文以便将其传递给我的对象工厂时:
_context = (IApplicationContext)ConfigurationManager.GetSection("spring/context");
我意识到我的 SimpleObject
被实例化。对我来说,这听起来很奇怪。这是正常的吗?我怎样才能避免这种情况?我只希望当我明确要求 _context
创建对象时创建对象。
I have a SimpleObject
class
public class SimpleObject
{
public SimpleObject()
{
Console.WriteLine("Instantiated");
}
}
and a simple Spring configuration:
<object id="simpleObject" type="SpringTest.SimpleObject, SpringTest" />
When I parse the configuration to get the context in order to pass it to my object factory with:
_context = (IApplicationContext)ConfigurationManager.GetSection("spring/context");
I realize that my SimpleObject
is instantiated. It sounds like a weird behavior to me. It is normal ? How can I avoid that ? I only want my object to be created when I explicitly ask _context
to create one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我看到您找到了适合您的配置...但这里是您问题的“为什么”部分的答案。
默认情况下,对象具有单例范围。 Spring 在构造容器时实例化单例。根据 文档 这样做是为了配置问题尽早检测,即在集装箱建造时检测。
您可以通过指定
lazy-init="true"
来覆盖对象定义中的此默认行为。然后,当第一次在容器上请求时,或者第一次需要构造另一个对象时,将创建单例。请注意,您还可以使用 ...
... 让容器中的所有对象的延迟初始化默认为 true。
I saw you found a configuration that works for you ... but here's an answer to the "why" part of your question.
By default, an object has singleton scope. Spring instantiates singletons when constructing the container. According to the docs this is done so configuration problems are detected as early as possible, namely at container construction time.
You can override this default behavior in the object definition by specifying
lazy-init="true"
. Then the singleton will be created when it is first requested on the container, or when it is first needed to construct another object.Note that you can also use ...
... to let lazy initialization default to true for all objects in the container.
好吧,我傻了,
这只是
Ok, I am stupid,
this was simply