On the difference between spring singleton bean and singleton pattern

The difference between spring singleton bean and singleton pattern is that their associated environment is different. Singleton pattern means that there is only one instance in a JVM process, while spring singleton means that there is only one instance in a spring bean container (ApplicationContext).

First look at the singleton mode, In a JVM process (theoretically, a running Java program must have its own independent JVM), there is only one instance. Therefore, no matter where the instance is obtained in the program, the same object is always returned. Take the built-in runtime in Java as an example (enumeration is now the best practice of singleton mode). The following judgment is always true whenever and where it is obtained:

In contrast, spring's singleton bean is closely related to its ApplicationContext. Therefore, in a JVM process, if there are multiple spring containers, even singleton beans, multiple instances will be created. The code example is as follows:

The following is the spring configuration file:

summary

Spring's singleton bean is closely related to the spring bean management container. Each container will create its own unique instance, so it is very different from the singleton pattern in GoF design pattern. However, in practical application, if the object life cycle is completely managed by spring (not created in other places through new, reflection, etc.), the singleton pattern can also be achieved.

The above is all about the difference between spring singleton bean and singleton mode. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>