Bean有7种作用域,只详细了解其中最常用的两种:singleton prototype
- singleton(单例):在每个Spring IoC容器中一个bean定义对应一个对象实例。
singleton是spring容器的默认作用域。
<bean id="scope" class="com.woongcha.scope.scope" scope="singleton"/>
public class ScopeTest {
public static void main(String[] args) {
String xmlPath = "com/woongcha/scope/beans4.xml";
//ApplicationContext在加载配置文件时,对Bean进行实例化
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
scope pig=new scope();
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
}
com.woongcha.scope.Scope@3a03464
com.woongcha.scope.Scope@3a03464
两次输出结果相同,说明spring容器之创建了一个Scope类的实例。
- prototype(原型):在每个Spring IoC容器中一个bean定义对应多个对象实例。
<bean id="scope" class="com.woongcha.scope.scope" scope="prototype"/>
com.woongcha.scope.scope@4157f54e
com.woongcha.scope.scope@90f6bfd
两次输出结果不相同,说明spring容器之创建了两个Scope类的实例。
Bean的生命周期
- singleton下的Bean的生命周期完全由Spring容器管理。
- prototype下的Bean的生命周期Spring容器只负责创建,其他过程都有客户端代码管理。