Can the object created in IoC container be called Singleton. If not - why?
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 conatin开发者_Python百科er exactly manages the objects..
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
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.
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.
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.)
You might find this Google Groups thread useful.
精彩评论