如何确保 Spring bean 是单例的?
我会实现接口(interface) ApplicationContext
, InitializingBean
和 BeanNameAware
.
在afterPropertiesSet()
我会调用isSingleton(String)
用 Bean 的名字。
还有其他方法可以确保 Bean 是单例吗?
因为 according to the API :
Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.
最佳答案
如果我没记错的话,默认情况下,spring 管理的 bean 将是单例(对于当前版本的 spring-library),除非您将范围定义为“原型(prototype)”类型。
检查:Default scope of spring beans
引用:
The singleton scope is the default scope in Spring
关于java - 确保 Spring bean 是单例的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9125518/