JavaEE Bean的两种常用作用域 singleton(单例)和prototype(原型)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/82807343

Spring4.3中为Bean的实例定义了其中作用域,这七种作用域中最常用的是singleton和prototype,今天就简单介绍这两个

作用域名称 说明
singleton(单例) 使用singleton定义的Bean在Spring容器中将只有一个实例,也就是说无论有多少个Bean在引用他,始终指向一个对象,这也是Spring容器默认的作用域,
prototype(原型) 每次通过Spring容器获取的prototype定义的Bean时,容器将创建一个新的Bean实例

一、singleton作用域

singleton是Spring默认的作用域,当Bean的作用域为singleton时,Spring容器就只会存在一个共享的Bean实例,并且所有对Bean的请求,只要id相同就会返回同一个Bean实例。singleton作用域对于无会话的Bean是最合适的选择。

1、在项目chapter02中创建一个com.itheima.scope包,在包中创建Scope类,该类不需要添加任何方法

package com.itheima.scope;

public class Scope {

}

2、然后创建一个配置文件beans4.xml,写入特定代码,如下面代码所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
        
        <bean id="scope1" class="com.itheima.scope.Scope" scope="singleton"/>
        <bean id="scope2" class="com.itheima.scope.Scope" scope="singleton"/>
        
</beans>

可以看到在xml中创建了两个bean且作用域均定义为singleton

3、在包中创建测试类,观察效果

package com.itheima.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ScopeTest4 {

	private static ApplicationContext beanlizi;

	public static void main(String[] args) {
		String xmlPath = "com/itheima/scope/beans4.xml";
		beanlizi = new ClassPathXmlApplicationContext(xmlPath);
		System.out.println(beanlizi.getBean("scope1"));
		System.out.println(beanlizi.getBean("scope1"));
		
		System.out.println(beanlizi.getBean("scope2"));
		System.out.println(beanlizi.getBean("scope2"));
		

	}

}

4、输出结果如下图所示:

一共四次发起Bean请求,输出了四次,但是只有两种不同的bean实例,这说明被定义作用于为singleton的bean如果请求id相同则会返回相同的bean实例

二、prototype作用域

对于需要保持会话的Bean(如:Struts2的Action类)应该使用prototype作用域。在使用prototype时,Spring容器会为每一个对Bean的请求都创建一个实例。

例如将上面例子中beans4.xml中两个bean的scope属性设置为prototype

再次运行测试类ScopeTest4,输出结果如下:

通过输出结果就会发现,四个bean实例各不相同,这就是bean的作用域的不同导致的

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/82807343