Sunday, 7 April 2019

Singleton Bean working in Spring

There are five main scopes for creating a bean in spring.
  1. singleton
  2. prototype
  3. request
  4. session
  5. global-session
 Singleton is default scope type if we don't mention any scope then its singleton by default. A general perception about spring singleton bean is that it behaves same as java singleton class but there are few fundamental differences. Spring IoC container creates only one object for singleton bean and store it in cache memory of all singleton beans. All requests for bean with same name or id will get the same object, It does not mean that class defined as bean is singleton also. lets take an example where we create two beans for same class with different bean name and id then spring will create two different objects in shared memory and will return object based upon name or id given in request.

@Configuration
public class AppConfig {
    @Bean(name={"sineltonTest"})
    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public singeltonTest getSingeltonTest() {
        return new singeltonTest();
    }
   
    @Bean (name={"sineltonTest1"})
    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public singeltonTest getSingeltonTest1() {
        return new singeltonTest();
    }
}

In above example spring will create two different objects for two beans ("sineltonTest", "sineltonTest1") in shared cache and if we use @Autowired with @Qualifire("singeltonTest1") then it will get object from cache created for bean with name "sineltonTest1" so bean is sigleton not the class. There is one more catch w.r.t singleton bean in spring that what happen when we create object of that class with new operator instead of @autowired? This question is asked basically to confuse the person in interview. The clear answer is that spring will not return object from cache now it depends upon exact implementation of the bean class if it is created as java singleton class then one instance is created and every time same instance will be returned otherwise every time new instance is created and returned.

No comments:

Post a Comment