7.4Java EE——Bean的作用域

一、singleton作用域

Spring支持的5种作用域

作用域名城

描述

singleton

单例模式。在单例模式下,Spring 容器中只会存在一个共享的Bean实例,

所有对Bean的请求,只要请求的id(或name)与Bean的定义相匹配,

会返回Bean的同一个实例。

prototype

原型模式,每次从容器中请求Bean时,都会产生一个新的实例。

request

每一个HTTP请求都会有自己的Bean实例,

该作用域只能在基于Web的Spring ApplicationContext中使用。

session

每一个HTTPsession请求都会有自己的Bean实例,

该作用域只能在基于Web的Spring ApplicationContext中使用。

global session

限定一个Bean的作用域为Web应用(HTTPsession)的生命周期,

只有在Web应用中使用Spring时,该作用域才有效。

1、 下面将通过案例的方式演示Spring容器中singleton作用域的使用。

<?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.xsd">
    <bean id="bean1" class="com.mac.Bean1" scope="singleton"></bean>
</beans>

2、创建测试类scopeTest,在main()方法中通过加载applicationBean1.xml配置文件初始化Spring容器,通过Spring容器获取Bean1类的两个实例,判断两个实例是否为同一个。

public class scopeTest{
    public static void main(String[] args){
        ApplicationContext applicationContext=new 
               ClassPathXmlApplicationContext("applicationBean1.xml");
        Bean1 bean1_1=(Bean1) applicationContext.getBean("bean1");
        Bean1 bean1_2=(Bean1) applicationContext.getBean("bean1");
        System.out.print(bean1_1==bean1_2);	}
}

 3、在IDEA中启动scopeTest类,控制台会输出运行结果。

 

 二、prototype作用域

singleton作用域知识点的基础上修改配置文件,将id为bean1的作用域设置为prototype。

<bean id="bean1" class="com.mac.Bean1" scope="prototype"></bean>

Guess you like

Origin blog.csdn.net/W_Fe5/article/details/131802908