为什么Spring.Net在解析配置时实例化对象?

发布于 2024-12-10 11:54:26 字数 685 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荒岛晴空 2024-12-17 11:54:26

我看到您找到了适合您的配置...但这里是您问题的“为什么”部分的答案。

默认情况下,对象具有单例范围。 Spring 在构造容器时实例化单例。根据 文档 这样做是为了配置问题尽早检测,即在集装箱建造时检测。

您可以通过指定lazy-init="true"来覆盖对象定义中的此默认行为。然后,当第一次在容器上请求时,或者第一次需要构造另一个对象时,将创建单例。

请注意,您还可以使用 ...

<objects default-lazy-init="true">
  <!-- no objects will be pre-instantiated... -->
</objects>

... 让容器中的所有对象的延迟初始化默认为 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 ...

<objects default-lazy-init="true">
  <!-- no objects will be pre-instantiated... -->
</objects>

... to let lazy initialization default to true for all objects in the container.

岛徒 2024-12-17 11:54:26

好吧,我傻了,

这只是

<object id="simpleObject" type="SpringTest.SimpleObject, SpringTest" lazy-init="true" />

Ok, I am stupid,

this was simply

<object id="simpleObject" type="SpringTest.SimpleObject, SpringTest" lazy-init="true" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文