There are five main scopes for creating a bean in spring.
@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.
- singleton
- prototype
- request
- session
- global-session
@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