Table of contents
2. The difference between singleton bean and prototype bean
3. Advantages and Disadvantages of Singleton Bean
1. Five scopes
1.singleton:
Singleton is the default scope of Spring Bean , which is the singleton mode. Throughout the application, only one instance will be created, and all requests for the bean will share this instance.
2.prototype:
Prototype represents prototype mode , and each request will create a new Bean instance. Therefore, you can have multiple instances in your application without affecting each other.
3.request:
request means creating a Bean instance within the scope of an HTTP request. Every time an HTTP request is made, a new Bean instance is created, which can only be used in the current request.
4.session:
session means creating a Bean instance within the HTTP session scope. During a session, only one Bean instance is created. If multiple requests are made during the same session, the requests will all share the same bean instance.
5.globalsession:
globalsession means creating a Bean instance within the scope of the global HTTP session. This scope only applies to portlet-based web applications. For other types of web applications, globalsession scope and session scope are the same.
2. The difference between singleton bean and prototype bean
If a bean is declared as a singleton, only one bean is instantiated in the Spring container when multiple requests are processed, and subsequent requests share this object, which will be saved in a map . When a request comes in, it will first check from the cache (map) , if there is, use this object directly, if not, instantiate a new object, so this is a singleton. But for the prototype (prototype) bean, a new bean is instantiated directly when each request comes in, there is no cache and the process of checking from the cache.
3. Advantages and Disadvantages of Singleton Bean
Advantage:
1. Reduce the consumption of newly generated instances: The consumption of newly generated instances includes two aspects. First, Spring will generate bean instances through reflection or cglib, which are all performance-consuming operations. Secondly, allocating memory to objects will also involve complex algorithms. .
2. Reduce JVM garbage collection : Since bean instances are not newly generated for every request, fewer objects are naturally recycled.
3. Beans can be obtained quickly: Because the bean acquisition operation of a singleton is obtained from the cache except for the first generation, it is very fast.
Disadvantages:
A big disadvantage of singleton beans is that they cannot be thread-safe! ! ! Since all requests share a bean instance, if this bean is a stateful bean, there may be problems in concurrent scenarios , while the prototype bean will not have such problems (but there are exceptions, such as he is dependent on a singleton bean), Because a new instance is created for every request.