xxxxxxxxxx
There are 5 types of bean scopes available, they are:
1) singleton: Returns a single bean instance per Spring IoC container.
2) prototype: Returns a new bean instance each time when requested.
3) request: Returns a single instance for every HTTP request call.
4. Session
5. GlobalSession
xxxxxxxxxx
- Bean : Java object that is managed by the IoC container
- Singleton
- default scope
- one instance of object per context
- You may declare two beans. But injecting them requires a lot more stuff (NOT RECOMMENDED)
- Spring keeps the handle of the object
- be careful with state data. since every class that have the dependency will have access to state data, it may get changed by some other thread.
- Prototype
- Creates new instance every time it is referenced
- useful for transient data or types that flex on states
- Spring hands over that instance and releases its own handle, so when the task is finished, it is automatically disposed off by garbage collector
- Session
- Works in web environment only
- One instance of bean per user session
- Helps to isolate session data from other sessions
- Spring hands over that instance and releases its own handle, so when the session is finished, it is automatically disposed off by garbage collector
- Request
- Works in web environment only
- One instance of bean per user request
- Spring hands over that instance and releases its own handle, so when the request is finished, it is automatically disposed off by garbage collector
xxxxxxxxxx
// NormalClass.java (We will make the scope singleton)
@Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON) // Default, does not matter even if you specify it explicitly
// @Scope("singleton")
@Component
class NormalClass {
// business logic
}
// PrototypeClass.java (We will make the scope prototype)
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
// @Scope("prototype")
@Component
class PrototypeClass {
// business logic
}
// BeanScopesLauncherApplication.java
@Configuration
@ComponentScan("com.your.package")
public class BeanScopesLauncherApplication {
public static void main(String[] args) {
try (var context =
new AnnotationConfigApplicationContext
(BeanScopesLauncherApplication.class)) {
System.out.println(context.getBean(NormalClass.class)); // singleton will show same object address
System.out.println(context.getBean(NormalClass.class)); // singleton will show same object address
System.out.println(context.getBean(NormalClass.class)); // singleton will show same object address
System.out.println(context.getBean(PrototypeClass.class)); // singleton will show different object address
System.out.println(context.getBean(PrototypeClass.class)); // singleton will show different object address
System.out.println(context.getBean(PrototypeClass.class)); // singleton will show different object address
}
}
}