Spring学习笔记——第五部分 Bean Scopes(Bean作用域)
1. singleton(单例模式)(默认)
- 该作用域会使所有的Bean请求,只要id与所需要的bean的id相同,就会返回同一个bean实例,singleton对于无会话状态的bean来说,是最好的选择。
<bean id="user2" class="com.zhang.pojo.User" c:name="C张作鹏" c:age="18" scope="singleton"/>
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("userMapper.xml");
User user = (User) context.getBean("user2");
User user2 = (User) context.getBean("user2");
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
System.out.println(user==user2);
}
hashcode相同,说明调用的是同一个对象
2. prototype(原型模式)
- 需要保持会话状态的bean(如Struts2的Action类)就应该使用prototype作用域。
- 在使用该作用域时,每一个bean请求都会创建一个新的实例。
hashcode不同,每次从容器中get时,都会产生一个新对象
3. request、session、application、websocket
这四种只在web开发中使用到