Spring中Bean的作用域
- 单例模式:(默认机制)
<bean id="user2" class="com.wbx.Student.User" c:uname="小余" c:age="520" scope="singleton"/>
测试:
@Test
public void testuser(){
ApplicationContext context = new ClassPathXmlApplicationContext("Userbeans.xml");
//此处的反射声明了类型,则不需要在进行强转
User user2 = context.getBean("user2", User.class);
User user = context.getBean("user2", User.class);
System.out.println(user==user2);
}
2. 原型模式:每次从容器get中,都会产生一个新对象
<bean id="user2" class="com.wbx.Student.User" c:uname="小余" c:age="520" scope="prototype"/>
测试:
@Test
public void testuser(){
ApplicationContext context = new ClassPathXmlApplicationContext("Userbeans.xml");
//此处的反射声明了类型,则不需要在进行强转
User user2 = context.getBean("user2", User.class);
User user = context.getBean("user2", User.class);
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
System.out.println(user==user2);
}
- 其余的request,session,application,这些只能在web开发中用到