程序笔记   发布时间:2022-07-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Spring文档之Bean概述大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

目录
  • 2.3.1 Bean命名
    • 在 Bean 定义之外给 Bean 取别名
  • 2.3.2 Bean实例化
    • 使用构造函数实例化
    • 使用静态工厂方法实例化
    • 使用实例工厂方法实例化
    • 确定 Bean 的运行时类型
Bean Overview

A Spring IoC container manages one or more beans. These beans are created with the configuration metadata that you supply to the container (for example, in the form of XML <bean/> definitions).

Spring IoC 容器管理一个或多个 bean。这些 bean 是使用您提供给容器的配置元数据创建的(例如,以 XML<bean/>定义的形式 )。

Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata:

  • A package-qualified class name: typically, the actual implementation class of the bean being defined.
  • Bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
  • References to other beans that are needed for the bean to do its work. These references are also called collaborators or dependencies.
  • Other configuration settings to set in the newly created object — for example, the size limit of the pool or the number of connections to use in a bean that manages a connection pool.

在容器本身内,这些 bean 定义表示为BeanDefinition 对象,其中包含(除其他信息外)以下元数据:

  • 包限定的类名:通常是定义的 bean 的实际实现类。
  • Bean 行为配置元素,它说明 Bean 在容器中的行为方式(范围、生命周期回调等)。
  • 对 bean 执行其工作所需的其他 bean 的引用。这些引用也称为协作者或依赖项。
  • 在新创建的对象中设置的其他配置设置——例如,池的大小限制或在管理连接池的 bean 中使用的连接数。

This metadata translates to a set of properties that make up each bean definition.

Property Explained in…
Class Instantiating Beans
Name Naming Beans
Scope Bean Scopes
Constructor arguments Dependency Injection
Properties Dependency Injection
Autowiring mode Autowiring Collaborators
Lazy initialization mode Lazy-initialized Beans
Initialization method Initialization Callbacks
Destruction method Destruction Callbacks
财产 在…中解释
班级 实例化 Bean
姓名 命名 Bean
范围 Bean 作用域
构造函数参数 依赖注入
特性 依赖注入
自动装配模式 自动装配合作者
延迟初始化模式 延迟初始化的 Bean
初始化方法 初始化回调
销毁方法 销毁回调

In addition to bean definitions that contain information on how to create a specific bean, the ApplicationContext implementations also permit the registration of existing objects that are created outside the container (by users). This is done by accessing the ApplicationContext’s BeanFactory through the getBeanFactory() method, which returns the BeanFactory DefaultListableBeanFactoryimplementation. DefaultListableBeanFactory supports this registration through the registerSingleton(..) and registerBeanDefinition(..) methods. However, typical applications work solely with beans defined through regular bean definition metadata.

除了包含有关如何创建特定 bean 的信息的 bean 定义之外,ApplicationContext实现还允许注册在容器外(由用户)创建的现有对象。这是通过getBeanFactory()返回 BeanFactoryDefaultListableBeanFactory实现的方法访问 ApplicationContext 的 BeanFactory 来完成的。DefaultListableBeanFactory 通过registerSingleton(..)registerBeanDefinition(..)方法支持此注册。但是,典型的应用程序仅使用通过常规 bean 定义元数据定义的 bean。

Bean metadata and manually supplied singleton instances need to be registered as early as possible, in order for the container to properly reason about them during autowiring and other introspection steps. While overriding existing metadata and existing singleton instances is supported to some degree, the registration of new beans at runtime (concurrently with live access to the factory) is not officially supported and may lead to concurrent access exceptions, inconsistent state in the bean container, or both.

注意:Bean 元数据和手动提供的单例实例需要尽早注册,以便容器在自动装配和其他内省步骤中正确推理它们。虽然在某种程度上支持覆盖现有元数据和现有单例实例,但官方不支持在运行时注册新 bean(与实时访问工厂同时)并可能导致并发访问异常、bean 容器中的状态不一致,或两个都。

2.3.1 Bean命名

Naming Beans

Every bean has one or more identifiers. These identifiers must be unique within the container that hosts the bean. A bean usually has only one identifier. However, if it requires more than one, the extra ones can be considered aliases.

每个 bean 都有一个或多个标识符。这些标识符在承载 bean 的容器中必须是唯一的。一个 bean 通常只有一个标识符。但是,如果它需要多个,则可以将多余的视为别名。

在基于 XML 的配置元数据中,您可以使用id属性、name属性或两者来指定 bean 标识符。该id属性允许您指定一个 ID。通常,这些名称是字母数字('myBean'、'someService' 等),但它们也可以包含特殊字符。如果要为 bean 引入其他别名,也可以在name 属性中指定它们,用逗号 ( ,)、分号 ( ;) 或空格分隔。作为历史记录,在 Spring 3.1 之前的版本中,id属性被定义为一种xsd:ID类型,它限制了可能的字符。从 3.1 开始,它被定义为一种xsd:string类型。请注意,bean 的id唯一性仍然由容器强制执行,但不再由 XML 解析器强制执行。

您不需要为 bean提供 aname或 an id。如果您没有明确提供 a nameid,则容器会为该 bean 生成一个唯一的名称。但是,如果您想通过名称引用该 bean,通过使用ref元素或服务定位器样式查找,您必须提供名称。不提供名称的动机与使用内部 bean和自动装配协作者有关。are related to using inner beans and autowiring collaborators.

Bean 命名约定

约定是在命名 bean 时对实例字段名称使用标准 Java 约定。也就是说,bean 名称以小写字母开头,并从那里开始使用驼峰式大小写。此类名称的示例包括accountManageraccountServiceuserDaologinController等等。

注意:通过类路径中的组件扫描,Spring 为未命名的组件生成 bean 名称,遵循前面描述的规则:本质上,采用简单的类名并将其初始字符转换为小写。但是,在有多个字符且第一个和第二个字符都是大写的(不寻常的)特殊情况下,原始大小写被保留。这些与定义的规则相同java.beans.Introspector.decapitalize(Spring 在这里使用)。

With component scanning in the classpath, Spring generates bean names for unnamed components, following the rules described earlier: essentially, taking the simple class name and turning its initial character to lower-case. However, in the (unusual) special case when there is more than one character and both the first and second characters are upper case, the original casing gets preserved. These are the same rules as defined by java.beans.Introspector.decapitalize (which Spring uses here).

在 Bean 定义之外给 Bean 取别名

Aliasing a Bean outside the Bean Definition

在bean定义本身中,您可以为bean提供多个名称,方法是使用id属性指定的最多一个名称和name属性中任意数量的其他名称的组合。这些名称可以是相同bean的等效别名,在某些情况下很有用,例如允许应用程序中的每个组件使用特定于该组件本身的bean名称来引用公共依赖项。

然而,在实际定义bean的地方指定所有别名并不总是足够的。有时需要为别处定义的bean引入别名。这种情况在大型系统中很常见,其中配置在每个子系统之间被分割,每个子系统都有自己的一组对象定义。在基于xml的配置元数据中,可以使用元素来完成此任务。 下面的例子展示了如何做到这一点:

<alias name="fromName" alias="toName"/>

在这种情况下,命名的 bean(在同一容器中)fromName也可以在使用此别名定义后称为toName.

例如,子系统 A 的配置元数据可能引用名为 的数据源subsystemA-dataSource。子系统 B 的配置元数据可以通过名称来引用数据源subsystemB-dataSource。在组合使用这两个子系统的主应用程序时,主应用程序通过名称引用 DataSource myApp-dataSource。要让所有三个名称都引用同一个对象,您可以将以下别名定义添加到配置元数据中:

<alias name="myApp-dataSource" alias="subsystemA-dataSource"/>
<alias name="myApp-dataSource" alias="subsystemB-dataSource"/>

现在,每个组件和主应用程序都可以通过一个唯一的名称来引用 dataSource,并且保证不会与任何其他定义发生冲突(有效地创建一个命名空间),但它们引用的是同一个 bean。

2.3.2 Bean实例化

Instantiating Beans

A bean definition is essentially a recipe for creating one or more objects. The container looks at the recipe for a named bean when asked and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object.

bean 定义本质上是创建一个或多个对象的配方。当被询问时,容器会查看命名 bean 的配方,并使用该 bean 定义封装的配置元数据来创建(或获取)实际对象。

If you use XML-based configuration metadata, you specify the type (or class) of object that is to be instantiated in the class attribute of the <bean/> element. This class attribute (which, internally, is a Class property on a BeanDefinition instance) is usually mandatory. (For exceptions, see Instantiation by Using an Instance Factory Method and Bean Definition Inheritance.) You can use the Class property in one of two ways:

如果使用基于 XML 的配置元数据,则指定要在元素的class属性中实例化的对象的类型(或类)<bean/>。这个 class属性(在内部,它是一个BeanDefinition 实例的Class属性)通常是强制性的。(对于例外情况,请参阅 使用实例工厂方法和Bean 定义继承进行实例化。)您可以通过以下Class两种方式之一使用该属性:

  • Typically, to specify the bean class to be constructed in the case where the container itself directly creates the bean by calling its constructor reflectively, somewhat equivalent to Java code with the newoperator. 通常,在容器本身通过反射调用其构造函数直接创建 bean 的情况下,指定要构造的 bean 类,有点等同于带有new运算符的Java 代码。
  • To specify the actual class containing the static factory method that is invoked to create the object, in the less common case where the container invokes a static factory method on a class to create the bean. The object type returned from the invocation of the static factory method may be the same class or another class entirely. 指定包含被调用以创建对象的static工厂方法的实际类,在不太常见的情况下,容器调用 类上的static工厂方法来创建 bean。调用static工厂方法返回的对象类型可能是同一个类,也可能完全是另一个类。

嵌套类名

如果要为嵌套类配置 bean 定义,可以使用嵌套类的二进制名称或源名称。

例如,如果您SomeThingcom.example包中调用了一个类,并且SomeThing该类有一个static名为的嵌套类OtherThing,则它们之间可以用美元符号 ( $) 或点 ( .)分隔。因此classbean 定义中的属性值将是com.example.SomeThing$OtherThingor com.example.SomeThing.OtherThing

使用构造函数实例化

当您通过构造函数方法创建 bean 时,所有普通类都可以被 Spring 使用并与 Spring 兼容。也就是说,正在开发的类不需要实现任何特定的接口或以特定的方式进行编码。只需指定 bean 类就足够了。但是,根据您对该特定 bean 使用的 IoC 类型,您可能需要一个默认(空)构造函数

Spring IoC 容器几乎可以管理您希望它管理的任何类。它不仅限于管理真正的 JavaBean。大多数 Spring 用户更喜欢实际的 JavaBeans,它只有一个默认(无参数)构造函数适当的 setter 和 getter,它们以容器中的属性为模型。

使用基于 XML 的配置元数据

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

有关向构造函数提供参数(如果需要)和在构造对象后设置对象实例属性的机制的详细信息,请参阅 注入依赖项。

使用静态工厂方法实例化

在定义使用静态工厂方法创建的 bean 时,使用class 属性来指定包含static工厂方法的类和命名factory-method为指定工厂方法本身名称的属性。您应该能够调用此方法(带有可选参数,如下所述)并返回一个活动对象,随后将其视为通过构造函数创建的。这种 bean 定义的一种用途是在遗留代码中调用static工厂。

以下 bean 定义指定通过调用工厂方法来创建 bean。定义中没有指定返回对象的类型(类),只指定包含工厂方法的类。在这个例子中,createInstance() 方法必须是静态方法。以下示例显示了如何指定工厂方法:

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>

以下示例显示了一个可以与前面的 bean 定义一起使用的类:

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

有关在工厂返回对象后向工厂方法提供(可选)参数和设置对象实例属性的机制的详细信息,请参阅详细依赖项和配置

使用实例工厂方法实例化

与通过静态工厂方法实例化类似,使用实例工厂方法实例化从容器中调用现有 bean 的非静态方法来创建新 bean。要使用此机制,请将class属性留空,并在factory-bean属性中指定当前(或父或祖先)容器中 bean 的名称,该容器包含要调用以创建对象的实例方法。使用factory-method属性设置工厂方法本身的名称。以下示例显示了如何配置此类 bean:

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

以下示例显示了相应的类:

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

一个工厂类也可以包含多个工厂方法,如下例所示:

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

<bean id="accountService"
    factory-bean="serviceLocator"
    factory-method="createAccountServiceInstance"/>

以下示例显示了相应的类:

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    private static AccountService accountService = new AccountServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }

    public AccountService createAccountServiceInstance() {
        return accountService;
    }
}

这种方法表明工厂 bean 本身可以通过依赖注入 (DI) 进行管理和配置。请参阅详细依赖项和配置。

注意:

在 Spring 文档中,“ factory bean”是指在 Spring 容器中配置并通过实例或 静态工厂方法创建对象的 bean 。相比之下, FactoryBean(注意大写)是指特定于 Spring 的 FactoryBean实现类。

确定 Bean 的运行时类型

确定特定 bean 的运行时类型并非易事。bean 元数据定义中的指定类只是一个初始类引用,可能与声明的工厂方法结合,或者是FactoryBean可能导致 bean 的不同运行时类型的类,或者在实例的情况下根本没有设置 -级别工厂方法(通过指定factory-bean名称解析)。此外,AOP 代理可以使用基于接口的代理包装 bean 实例,并限制暴露目标 bean 的实际类型(仅其实现的接口)。

找出特定 bean 的实际运行时类型的推荐方法是BeanFactory.getType调用指定的 bean 名称。这考虑了上述所有情况,并返回BeanFactory.getBean调用将返回的相同 bean 名称的对象类型。

大佬总结

以上是大佬教程为你收集整理的Spring文档之Bean概述全部内容,希望文章能够帮你解决Spring文档之Bean概述所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: