我在这里可能是错的,但我无法弄清楚为什么 Spring 从 Singleton 类创建 2 个不同的对象。代码如下:
public class DbSingleTOn {
private static DbSingleTOn dbSingleTOn = new DbSingleTOn();
private DbSingleTOn() {
}
public static DbSingleTOn getInstance() {
return dbSingleTOn;
}
}
public class MyApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"spring-singleton.xml");
DbSingleTOn dbSingleTOn = context.getBean(DbSingleTOn.class);
System.out.println(dbSingleTOn.hashCode());
DbSingleTOn dbSingleTOn1 = context.getBean(DbSingleTOn.class);
System.out.println(dbSingleTOn1.hashCode());
context.registerShutdownHook();
}
}
Output:
18885489
17045421
Spring 配置 XML:
<bean id="bean1" class="com.singleton.DbSingleTOn" scope="prototype" >
</bean>
预计使用“原型(prototype)”作用域为普通类获取不同的对象,但是,为什么“原型(prototype)”会从 Singleton 类创建 2 个对象?
最佳答案
仅仅因为您在静态字段中创建了单例,这不会对 spring 产生影响。 Spring根本没有意识到这一点。
原型(prototype)范围仅意味着:在调用 getBean
时返回一个新实例。
单例范围意味着:创建一个实例一次并始终返回该实例。
关于java - 为什么 Spring 会从 Singleton 类创建 2 个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28255135/