views:

99

answers:

5

can the object created in IOC container can be called Singleton if yes why if no why?

Can anybody explain me in detail in simple words how IOC conatiner exactly manages the objects..

+1  A: 

Spring (and other ioc-containers) offer different scopes. One of the scopes is singleton - i.e. the container instantiates the object only once and gives / injects only one instance. Singleton is the default scope, so most of the beans are indeed singletons from the point of view of the container- i.e. they have only one instance in it.

However, there are other scopes, like prototype or the web-based request and session.

In managing the bean, the container does the following:

  • invokes the @PostConstruct and @PreDestroy methods (or the init and destroy methods, configured by any available means)
  • injects all their defined dependencies (=sets other beans existing in the container to the fields of this bean)
  • creates AOP aspects around the bean methods

Note: you can instantiate more than one objects of a class that is defined as as singleton bean. The container instantiates the object only once, but your code is not limited to instantiating it multiple times.

Bozho
request scope means object is created per http request and session means object per user. M i correct ??
taher
yes, that's correct.
Bozho
A: 

you might find the following useful: http://bit.ly/beSM90

Philip Schwarz
maybe so, but I'll never follow that link if you don't describe it in a sentence or so ...
seanizer
+4  A: 

You can say that a spring singleton is not a singleton.

Singleton has its meaningful scope, the spring singleton scope is the spring ioc container. And the classic singleton's meaningful scope is the ClassLoader. You may find more about the distinction between these kinds of singleton here: A spring singleton is not a singleton.

Spring manage its singleton in a hashmap(Singleton Cache). When you get a bean from the spring ioc container, it first checks if the bean has already exists in the singleton cache, if does, it returns the bean from the singleton cache

khotyn
A: 

can the object created in IOC container can be called Singleton if yes why if no why?

Read this, from the Spring Reference.

Can anybody explain me in detail in simple words how IOC conatiner exactly manages the objects..

Read this, from the Spring Reference.

James Earl Douglas
A: 

I use a more generic definition of a Singleton:

A Singleton is an object that is guaranteed to be unique inside a given scope.

This scope is the ClassLoader in the traditional singleton definition, but other possible scopes are:

  • Application (may be clustered and therefor classic Singleton won't help)
  • HTTP Session
  • Thread (implemented through ThreadLocals)
  • HTTP Request etc.

(I really like the Seam method Component.getInstance(Class, ScopeType) that lets you choose the Scope you want a singleton for.)

seanizer