Bean的作用范围scope
在Spring配置文件中的<bean>标签可以指定bean的作用范围
利用<bean>标签中的scope属性来指定
scope值:
1、 singleton单例:每次取出的bean都是同一个bean。默认就是这个
2、 prototype原型:每次取的bean时,都会重新创建一个新的bean
3、 request
4、 session
5、 globalsession
实例:
<bean id="u" class="com.sxt.dao.impl.UserDaoImpl" ></bean>
<bean name="userService" class="com.sxt.service.UserService" scope="prototype">
<property name="userDao" ref="u"/>
</bean>
注意:只有spring与web框架结合时才会使用request/session/globalsession,但也非常少用,因为其它框架已经有功能非常强大的scope了(例如:struts的scope)
如测试scope 为singleton
public void testAdd() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //取id为userService的bean的对象两次,结果发现他们的引用地址相同. UserService service = (UserService)ctx.getBean("userService"); UserService service2 = (UserService)ctx.getBean("userService"); System.out.println(service == service2); //打印true , 说明每次取的是同一个对象 User u = new User(); u.setUsername("zhangsan"); u.setPassword("zhangsan"); service.add(u); } |
如测试scope 为prototype
用以上同一个测试代码:
打印出来就是false