Spring Framework Documentation (5.3.10)
Core | IoC Container, Events, Resources, i18n, Validation, Data Binding, Type Conversion, SpEL, AOP. |
1. The IoC Container
1.1. Introduction to the Spring IoC Container and Beans(Spring IoC容器和bean简介)
1.2. Container Overview (容器概览)
1.3.1.1Aliasing a Bean outside the Bean Definition 在Bean定义外指定Bean别名
1.3.2. Instantiating Beans实例化bean
1.3.2.1.Instantiation with a Constructor (通过构造函数进行实例化)
1.3.2.2. Instantiation with a Static Factory Method (通过静态工厂方法进行实例化)
1.3.2.3. Instantiation by Using an Instance Factory Method (使用实例工厂方法进行实例化)
1.3.2.4. Determining a Bean’s Runtime Type(确定Bean的运行时类型)
下载此文档精编完整版
No. | 内容 | 下载地址 | 文档内容目录 |
1 | 中英双语精编版 第一部分 | PDF下载 | 内容目录 |
2 | 中英双语精编版 第二部分 | PDF下载 | 内容目录 |
3 | 中文精编版 第一部分 | PDF下载 | 内容目录 |
4 | 中文精编版 第二部分 | PDF下载 | 内容目录 |
更多章节内容,请点击查看: Core Technologies
1.3.2.2. Instantiation with a Static Factory Method (通过静态工厂方法进行实例化)
When defining a bean that you create with a static factory method, use the class
attribute to specify the class that contains the static
factory method and an attribute named factory-method
to specify the name of the factory method itself. You should be able to call this method (with optional arguments, as described later) and return a live object, which subsequently is treated as if it had been created through a constructor. One use for such a bean definition is to call static
factories in legacy code.
在定义采用使用静态工厂方法创建的bean时,请使用class属性指定包含static
工厂方法的类,并使用名为 factory-method
的属性指定该工厂方法的名称。您应该能够调用此方法(使用可选参数,如下文所述)并返回一个活动对象(live object),该对象随后将被视为是通过构造函数创建的。这种bean定义的一个用途是在遗留代码中调用静态工厂。
The following bean definition specifies that the bean be created by calling a factory method. The definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, the createInstance()
method must be a static method. The following example shows how to specify a factory method:
下面的bean定义指定采用调用工厂方法来创建bean。该定义没有指定返回对象的类型(类),只指定了包含工厂方法的类。在本例中,createInstance
() 方法必须是静态方法。以下示例展示如何指定工厂方法:
<bean id="clientService"
class="examples.ClientService"
factory-method="createInstance"/>
The following example shows a class that would work with the preceding bean definition:
以下示例展示了一个可与前述bean定义一起使用的类:
Java
public class ClientService {
private static ClientService clientService = new ClientService() ;
private ClientService() {}
public static ClientService createInstance() {
return clientService;
}
}
Kotlin
class ClientService private constructor () {
companion object {
private val clientService = ClientService()
fun createInstance() = clientService
}
}
For details about the mechanism for supplying (optional) arguments to the factory method and setting object instance properties after the object is returned from the factory, see Dependencies and Configuration in Detail.
在对象从工厂返回后,有关向工厂方法提供(可选)参数和设置对象实例属性的机制的详细信息,请参阅依赖项和配置详情(Dependencies and Configuration in Detail)。