我可能在這裏錯了,但我無法弄清楚爲什麼Spring會從Singleton類創建2個不同的對象。以下是代碼:爲什麼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>
預計使用「原型」的範圍,但是,爲什麼會「原型」創建2個對象,以得到一個正常的類不同的對象來自Singleton類?
@Scotirios我有一個預感,Spring必須通過反射來加載類,因此是預期的行爲。感謝您的確認。 – bluelurker 2015-01-31 18:45:01