The difference between Spring singleton beans and singleton patterns is that they are associated with different environments. Singleton patterns refer to only one instance in a JVM process, while Spring singleton refers to only one instance in a Spring bean container (ApplicationContext).
First, look at the singleton pattern. In a JVM process (theoretically, a running JAVA program must have its own independent JVM) there is only one instance, so no matter where the instance is obtained in the program, the same object is always returned. Taking the built-in Runtime in Java as an example (the enumeration is now the best practice of singleton pattern), no matter where the time and where it is obtained, the following judgment is always true:
// Based on lazy mode // There is always only one instance in a JVM instance Runtime.getRuntime() == Runtime.getRuntime()
In contrast, Spring's singleton beans are closely related to their containers (ApplicationContext). Therefore, in a JVM process, if there are multiple Spring containers, even a singleton bean will definitely create multiple instances. The code example is as follows:
// The first Spring Bean container ApplicationContext context_1 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml"); Person yiifaa_1 = context_1.getBean("yiifaa", Person.class);// The second Spring Bean container ApplicationContext context_2 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml"); Person yiifaa_2 = context_2.getBean("yiifaa", Person.class);// This is definitely not equal, because multiple instances are created System.out.println(yiifaa_1 == yiifaa_2);Here is the Spring configuration file:
<!-- Even if it is declared as a singleton, multiple instances will be created as long as there are multiple containers --><bean id="yiifaa" scope="singleton"> <constructor-arg name="username"> <value>yiifaa</value> </constructor-arg></bean>
Summarize
Spring's singleton beans are closely related to Spring bean management containers. Each container will create its own unique instance, so it is very different from the singleton pattern in the GOF design pattern. However, in actual applications, if the life cycle of the object is completely handed over to Spring management (not created by new, reflection, etc. elsewhere), the effect of the singleton pattern can actually be achieved.
The above is all about this article discussing the difference between Spring singleton bean and singleton model. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!