Spring单例和Java singeleton(设计模式)有什么区别? [英] What is the difference between a Spring singleton and a Java singeleton(design pattern)?

查看:155
本文介绍了Spring单例和Java singeleton(设计模式)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Spring框架,目前正在阅读一本关于它的书。
在本书中它说Spring单例与Java单例不同?
这是什么意思,有什么区别?
谢谢

I am learning Spring framework and currently reading a book about it. In this book it says that a Spring singleton is different from a Java singleton? What does this mean and what are the differences? Thanks

推荐答案

Java单例由Java类加载器限定,Spring单例由容器上下文限定。

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.

这基本上意味着,在Java中,你可以确定单例是一个真正的单例,只在加载它的类加载器的上下文中。其他类加载器应该能够创建它的另一个实例(假设类加载器不在同一个类加载器层次结构中),尽管你在代码中努力阻止它。

Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.

在Spring中,如果你可以在两个不同的上下文中加载你的单例类,那么我们可以再次打破单例概念。

In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.

所以,总的来说,Java如果它不能在给定的类加载器中创建该类的多个实例,则认为某个单例是单例,而如果它不能在给定的容器/上下文中创建多个类的实例,则Spring会认为它是单例。

So, in summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.

这篇关于Spring单例和Java singeleton(设计模式)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆