Spring Note 6: beans作用域

When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.

singleton

假设beans.xml:

1
2
3
<bean name="userService" class="Service.UserServiceImpl" scope="singleton">
<property name="userDao" ref="userDao"/>
</bean>

那么通过这个bean创建的对象,地址都是一样的。
MyTest.java:

1
2
3
UserService userService = (UserService) classPathXmlApplicationContext.getBean("userService");
UserService userService2 = (UserService) classPathXmlApplicationContext.getBean("userService");
System.out.println(userService==userService2);

输出:

1
true

prototype

同上,如果把bean中的scope属性的值改为prototype,那么每一次使用这个bean都会创建一个新的对象。
输出:

1
false

总结

  1. singleton在容器中,只被实例化一次,而prototype在容器中,调用几次,就被实例化几次;
  2. 在AppplicationContext容器中,singleton在applicaitonContext.xml加载时就被预先实例化,而prototype必须在调用时才实例化
  3. singleton比prototype消耗性能,在web开发中,推荐使用singleton模式,在app开发中,推荐使用prototype模式。