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.
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.