Bean Scope
By default all the bean are created as Singletone bean in the spring application context.
No matter how many times the bean is getting used with injection but the same bean is used everywhere.
But many times some beans maintain the state. So, in such scenario its not good to use the singleton bean everywhere. Because it is not safe.
There are following scopes provided by Spring for the bean:
1) Singleton: One instance of the bean for whole application context.
4) Request : For each request new Instance of the bean is create.
2) Prototype :One instance of the bean is created whenever a bean is injected or retrieved from the Spring Application Context.
3) Session : For each session in the application a new instance of the bean will be created
Example:
If you are using Component Scanning:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserData { ... }
In java based Configuration with @Bean:
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public UserData userData() {
return new UserData();
}
With XML:
<bean id="notepad" class="com.myapp.UserData" scope="prototype" />