我阅读了关于 spring bean 范围的教程,因为他们提到如果 bean 范围是prototype
Spring 容器将在每个context.getBean("id")
语句中创建新对象。如果我们指定范围singleton
,即使我们写context.getBean("id")
了两次或更多次语句,它也只会创建一个对象......我做了一个小例子
Demo.java
public class Demo {
public static void main(String[] args)
{
ApplicationContext con=new ClassPathXmlApplicationContext("spconfig.xml");
Person p=(Person)con.getBean("person");
Person q=(Person)con.getBean("person");
System.out.println(" P hashCode :"+p.hashCode());
System.out.println(" Q hashCode :"+q.hashCode());
if (p==q)
{
System.out.println("Same instance!");
}
else {
System.out.println("Different instance");
}
}
}
上面的程序打印
P hashCode :18303751
Q hashCode :18303751
Same instance!
但是在Person
bean 范围内,我给出了scope="prototype"
为什么它打印相同的 Hashcode ????
解释一下任何人...
提前致谢...
spconfig.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="person" class="demo.Person" scope="prototype">
<property name="name" value="Hello World" />
</bean>
</beans>
人.java
package demo;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printHello() {
System.out.println("Hello ! " + name);
}
@Override
public int hashCode() {
return super.hashCode();
}
}