0
点赞
收藏
分享

微信扫一扫

Spring-Bean Definition

悲催博士僧 2021-09-21 阅读 63

构成应用程序主干并由springioc容器管理的对象称为bean。bean是由springioc容器实例化、组装和管理的对象。这些bean是使用提供给容器的配置元数据创建的。

例如,以XML<bean/>定义的形式。

Bean定义包含一个叫做配置元数据的信息,容器需要知道以下内容:

    • 创建Bean。
    • Bean的生命周期详细信息。
    • Spring Bean依赖关系。

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

序号

属性和说明

1个

class

此属性是必需的,它指定用于创建Bean的Bean类。

2个

name

此属性唯一地指定Bean标识符。在基于XML的配置元数据中,可以使用id和/或name属性来指定Bean标识符。

3

scope

此属性指定从特定bean定义创建的对象的范围

4

constructor-arg

这用于注入依赖关系

5

properties

这用于注入依赖关系

6

autowiring mode

这用于注入依赖关系

7

lazy-initialization mode

延迟初始化的bean告诉IoC容器在首次请求时(而不是在启动时)创建一个bean实例。

8

initialization method

容器设置完bean的所有必需属性后,将调用此回调

9

destruction method

当包含该bean的容器被销毁时要使用的回调

Spring 配置元数据

springioc容器与实际写入配置元数据的格式完全分离。以下是向Spring容器提供配置元数据的三种重要方法:

  • 基于XML的配置文件
  • 基于注释的配置
  • 基于Java的配置

以下例子是具有不同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>

举报

相关推荐

0 条评论