Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 conatiner exactly manages the objects..

like image 557
TaherT Avatar asked Aug 30 '10 08:08

TaherT


2 Answers

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

like image 111
khotyn Avatar answered Oct 13 '22 22:10

khotyn


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.

like image 30
Bozho Avatar answered Oct 13 '22 23:10

Bozho