Spring 简明教程

Spring - Bean Scopes

在定义 <bean> 时,您可以选择声明该 bean 的作用域。例如,要强制 Spring 在每次需要一个 bean 实例时生成一个新的 bean 实例,您应该将 bean 的作用域属性声明为 prototype 。类似地,如果您希望 Spring 在每次需要一个 bean 实例时返回同一个 bean 实例,您应该将 bean 的作用域属性声明为 singleton

When defining a <bean> you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean’s scope attribute to be prototype. Similarly, if you want Spring to return the same bean instance each time one is needed, you should declare the bean’s scope attribute to be singleton.

Spring 框架支持以下五个作用域,其中三个仅在您使用 web 感知 ApplicationContext 时可用。

The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext.

Sr.No.

Scope & Description

1

singleton This scopes the bean definition to a single instance per Spring IoC container (default).

2

prototype This scopes a single bean definition to have any number of object instances.

3

request This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.

4

session This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

5

global-session This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

在本章中,我们将讨论前两个作用域,其余三个将在我们讨论 web 感知 Spring ApplicationContext 时进行讨论。

In this chapter, we will discuss about the first two scopes and the remaining three will be discussed when we discuss about web-aware Spring ApplicationContext.

The singleton scope

如果将作用域设置为 singleton,则 Spring IoC 容器会为该 bean 定义所定义的对象创建恰好一个实例。此单个实例存储在这些 singleton bean 的缓存中,并且对该已命名 bean 的所有后续请求和引用都会返回缓存对象。

If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

默认作用域始终是单例。但是,当您只需要一个 bean 实例时,可以如以下代码片段所示在 bean 配置文件中设置 scope * property to *singleton

The default scope is always singleton. However, when you need one and only one instance of a bean, you can set the scope * property to *singleton in the bean configuration file, as shown in the following code snippet −

<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Example

让我们准备一个可用的 Eclipse IDE,然后执行以下步骤来创建一个 Spring 应用程序−

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps

Description

1

Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.

2

Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.

3

Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.

4

Create Beans configuration file Beans.xml under the src folder.

5

The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下是 HelloWorld.java 文件的内容 −

Here is the content of HelloWorld.java file −

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下是 MainApp.java 文件的内容−

Following is the content of the MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

以下是 singleton 作用域所需的配置文件 Beans.xml

Following is the configuration file Beans.xml required for singleton scope −

<?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-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "singleton">
   </bean>

</beans>

完成源文件和 Bean 配置文件创建后,我们运行该应用程序。如果您的应用程序一切正常,它将打印以下消息−

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Your Message : I'm object A
Your Message : I'm object A

The prototype scope

如果将作用域设置为 prototype,则 Spring IoC 容器会在每次对特定 bean 发出请求时为该对象创建一个新的 bean 实例。一般而言,将 prototype 作用域用于所有有状态 bean,将 singleton 作用域用于无状态 bean。

If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

要定义 prototype 作用域,可以在 bean 配置文件中将属性 scope 设置为 prototype ,如以下代码片段所示 −

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet −

<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Example

让我们启动 Eclipse IDE 并按照以下步骤创建一个 Spring 应用程序 −

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −

Steps

Description

1

Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.

2

Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.

3

Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.

4

Create Beans configuration file Beans.xml under the src folder.

5

The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下是 HelloWorld.java 文件的内容

Here is the content of HelloWorld.java file

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下是 MainApp.java 文件的内容−

Following is the content of the MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

以下是 prototype 作用域所需的配置文件 Beans.xml

Following is the configuration file Beans.xml required for prototype scope −

<?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-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "prototype">
   </bean>

</beans>

完成源文件和 Bean 配置文件创建后,我们运行该应用程序。如果您的应用程序一切正常,它将打印以下消息−

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Your Message : I'm object A
Your Message : null