单例模式是指在一个JVM进程中仅有一个实例,而Spring单例是指一个Spring Bean容器(ApplicationContext)中仅有一个实例
在一个JVM进程中,即使我们的bean是单例的,但是如果存在多个ApplicationContext容器,也会创建多个实例
// 第一个Spring Bean容器
ApplicationContext context_1 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Person stu_1 = context_1.getBean("student", Person.class);
// 第二个Spring Bean容器
ApplicationContext context_2 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Person stu_2 = context_2.getBean("student", Person.class);
// 这里绝对不会相等,因为创建了多个实例
System.out.println(stu_1 == stu_2);
Spring的单例bean与Spring bean管理容器密切相关,每个容器都会创建自己独有的实例,所以与GOF设计模式中的单例模式相差极大,但在实际应用中,如果将对象的生命周期完全交给Spring管理(不在其他地方通过new、反射等方式创建),其实也能达到单例模式的效果。