Spring bean定义

形成应用程序的骨干是由Spring IoC容器所管理的对象称为bean。bean被实例化,组装,并通过Spring IoC容器所管理的对象。这些bean由容器提供,例如,在XML的<bean/>定义,已经看到了前几章的形式配置元数据创建。

bean定义包含所需要的容器要知道以下称为配置元数据的信息:

  • 如何创建一个bean

  • Bean 生命周期的详细信息

  • Bean 依赖关系

上述所有配置元数据转换成一组的下列属性构成每个bean的定义。

属性 描述
class 此属性是强制性的,并指定bean类被用来创建bean。
name 此属性指定唯一bean标识符。在基于XML的配置元数据时,您可以使用id和/或name属性来指定bean标识符
scope 该属性指定一个特定的bean定义创建,它会在bean作用域本章要讨论的对象范围。
constructor-arg 这是用来注入的依赖关系,并在接下来的章节中进行讨论。
properties 这是用来注入的依赖关系,并在接下来的章节中进行讨论。
autowiring mode 这是用来注入的依赖关系,并在接下来的章节中进行讨论。
lazy-initialization mode 延迟初始化的bean告诉IoC容器创建bean实例时,它首先要求,而不是在启动时。
initialization method 回调只是在bean的所有必要属性后调用已设置的容器。它会在bean的生命周期章节中讨论。
destruction method 当包含该bean容器被销毁所使用的回调。它会在bean的生命周期章节中讨论。

 

Spring配置元数据

Spring IoC容器完全由在此配置元数据实际写入的格式解耦。有下列提供的配置元数据的Spring容器三个重要的方法:

  1. 基于XML的配置文件。

  2. 基于注解的配置

  3. 基于Java的配置

我们已经看到了基于XML的配置元数据如何提供给容器,但让我们看到了不同的bean定义,包括延迟初始化,初始化方法和销毁方法基于XML配置文件的另一个示例:

<?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">

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

   <!-- A bean definition with lazy init set on -->
   <bean id="..." class="..." lazy-init="true">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

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

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

   <!-- more bean definitions go here -->

</beans>

可以查看Spring Hello World 示例 来了解如何定义,配置和创建Spring Bean。 

有关基于注解的配置在一个单独的章节讨论。在一个单独的章节刻意保留它,因为希望能掌握一些Spring其他的重要概念,在开始用注解依赖注入来编程。