Spring支持以下Bean的作用域
其中后四种只在Web环境中有效,且Spring允许我们自定义Bean的作用域。
单例作用域(singleton)
Spring默认Bean的作用域是单例的。
当我们指定该Bean的作用域为单例后,无论我们从Spring容器中获取该Bean多少次,获取到的都是同一个实例。
Spring只会为单例的Bean创建一次实例对象。
代码如下:
<!-- 该Bean的作用域是单例的-->
<bean id="catSingleton" class="edu.hrbu.spring.bean.Cat" scope="singleton"/>
@Test
public void testSingleton() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
Cat cat1 = context.getBean("catSingleton", Cat.class);
Cat cat2 = context.getBean("catSingleton", Cat.class);
System.out.println("cat1 == cat2 @" + (cat1 == cat2));
}
运行结果:
原型作用域(prototype)
当我们指定该Bean的作用域为原型后,我们每从Spring容器中获取一次该Bean,每次得到的都是一个新的实例。
代码如下:
<!-- 该Bean的作用域是原型的-->
<bean id="catPrototype" class="edu.hrbu.spring.bean.Cat" scope="prototype"/>
@Test
public void testPrototype() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
Cat cat1 = context.getBean("catPrototype", Cat.class);
Cat cat2 = context.getBean("catPrototype", Cat.class);
System.out.println("cat1 == cat2 @" + (cat1 == cat2));
}
运行结果:
总结:
Spring容器对Bean的作用域有六种支持,并且允许我们自定义Bean的作用域。
只有单例作用域(singleton)和原型作用域(prototype)不需要在Web环境,其它四种需要Web环境。
对于singleton的Bean,Spring容器只会对该Bean进行一次实例化,无论我们获取多少次singleton的Bean,获取到的都是同一个Bean的实例。
对于prototype的Bean,我们获取一次该Bean的,Spring容器都会新创建该Bean的一个实例,我们每获取一次prototype的Bean,获取到的都是这个Bean的新的实例。