1.单例模式(Singleton)Spring默认机制
<bean id="getUser" class="com.cbbpp.pojo.User" scope="singleton">
<property name="name" value="111"></property>
</bean>
测试:
@Test
public void User(){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
User user1 = (User) context.getBean("getUser");
User user2 = (User) context.getBean("getUser");
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
System.out.println(user1==user2);
}
控制台结果:
278934944
278934944
true
Process finished with exit code 0
说明了每次从容器种get的时候,都是同一个对象
2.原型模式(prototype)
<bean id="getUser" class="com.cbbpp.pojo.User" scope="prototype">
<property name="name" value="111"></property>
</bean>
测试:
@Test
public void User(){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
User user1 = (User) context.getBean("getUser");
User user2 = (User) context.getBean("getUser");
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
System.out.println(user1==user2);
}
控制台结果:
282828951
394721749
false
Process finished with exit code 0
说明了每次从容器种get的时候,都是产生一个新的对象