- 通过Bean的scope属性来指定
- 常用的两种为:singleton和prototype
- 如果不设置scope属性的话,默认为singleton
- 创建一个类
public class Scope {
}
- 设置xml文件
<bean id="scope" class="com.mason.scope.Scope"/>
- 测试一下
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring.xml");
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
输出:
com.mason.scope.Scope@42e26948
com.mason.scope.Scope@42e26948
说明Spring容器只创建了一个Scope类的实例
但是如果设置scope为prototype
<bean id="scope" class="com.mason.scope.Scope" scope="prototype"/>
输出结果为:
com.mason.scope.Scope@6a41eaa2
com.mason.scope.Scope@7cd62f43