Spring中bean的作用域

tech2022-10-28  114

作用域scope配置项

作用域限定了Spring Bean的作用范围,在Spring配置文件定义Bean时,通过声明scope配置项,可以灵活定义Bean的作用范围。例如,当你希望每次IOC容器返回的Bean是同一个实例时,可以设置scope为singleton;当你希望每次IOC容器返回的Bean实例是一个新的实例时,可以设置scope为prototype。

scope配置项有5个属性,用于描述不同的作用域。

① singleton

使用该属性定义Bean时,IOC容器仅创建一个Bean实例,IOC容器每次返回的是同一个Bean实例。

② prototype

使用该属性定义Bean时,IOC容器可以创建多个Bean实例,每次返回的都是一个新的实例。

③ request

该属性仅对HTTP请求产生作用,使用该属性定义Bean时,每次HTTP请求都会创建一个新的Bean,适用于WebApplicationContext环境。

④ session

该属性仅用于HTTP Session,同一个Session共享一个Bean实例。不同Session使用不同的实例。

⑤ global-session

该属性仅用于HTTP Session,同session作用域不同的是,所有的Session共享一个Bean实例。

这里我们重点讨论singleton、prototype 作用域,request、session和global-session类作用域放到Spring MVC章节讨论,这里不再做详细讲述。

这里我们写个Student类用于测试

public class Student { private Integer sid; private String sname; public Student() { System.out.println("Student的构造方法"); } public Student(Integer sid, String sname) { this.sid = sid; this.sname = sname; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } // @Override // public String toString() { // return "Student{" + // "sid=" + sid + // ", sname='" + sname + '\'' + // '}'; // } }

1.singleton作用域

singleton是默认的作用域,当定义Bean时,如果没有指定scope配置项,Bean的作用域被默认为singleton。singleton属于单例模式,在整个系统上下文环境中,仅有一个Bean实例。也就是说,在整个系统上下文环境中,你通过Spring IOC获取的都是同一个实例。

例如这里我们写个例子配置Bean为singleton作用域的配置代码如下。

<bean id="student" class="com.atguigu.spring.day02_Spring.Student" scope="singleton"> <property name="sid" value="1001"/> <property name="sname" value="亚索"/> </bean>

写个Test类测试单例

public class Test { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("scope.xml"); Student s1 = ac.getBean("student", Student.class); Student s2 = ac.getBean("student", Student.class); System.out.println(s1); System.out.println(s2); } }

则输出结果: 构造方法只是运行了一次

这里如果我们把代码注释一部分:

public class Test { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("scope.xml"); // Student s1 = ac.getBean("student", Student.class); // Student s2 = ac.getBean("student", Student.class); // System.out.println(s1); // System.out.println(s2); } }

运行结果:

所以若spring中有单例模式的bean,在初始化容器时就会创建此对象。 而多例即原型的bean则在使用时创建。

2.prototype作用域

当一个Bean的作用域被定义prototype时,意味着程序每次从IOC容器获取的Bean都是一个新的实例。因此,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。

配置Bean为singleton作用域的配置代码如下。

<bean id="student" class="com.atguigu.spring.day02_Spring.Student" scope="prototype"> <property name="sid" value="1001"/> <property name="sname" value="亚索"/> </bean>

再次运行Test输出结果为: 说明添加prototype作用域后,IOC容器每次返回的都是一个新的实例。

总结: Spring IOC容器创建一个Bean实例时,可以为Bean指定实例的作用域,作用域包括singleton(单例模式)、prototype(原型模式)、request(HTTP请求)、session(会话)、global-session(全局会话)。

本文介绍了singleton和prototype模式,这两个模式的作用域在Spring框架中是经常用到的。对于singleton作用域的Bean,IOC容器每次都返回同一个实例,而prototype作用域的Bean,IOC容器每次产生一个新的实例。

最新回复(0)