spring 框架说明文档学习记录(3.1)

来源:互联网 发布:网络龙虎斗赌博揭秘 编辑:程序博客网 时间:2024/06/05 04:38

三.一   Beans简介

容器中bean定义对象的元数据

  • 一个包名限定的类:一般是bean定义的实现类
  • Bean行为定义元素,表明在容器中bean的表现(范围、生命周期回收等等)
  • 完成工作所需的对其他beans的引用;这些引用也被称为合作或依赖
  • 新创建对象中其他的配置设置,例如,一个连接池bean可用的连接数或者连接池大小

这些元数据表现为一系列组成bean定义的属性

  • class
  • name
  • scope
  • constructor arguments
  • properties
  • autowiring mode
  • lazy-initialization mode
  • initialization method
  • destruction method

----------------------------------------------------------------------------------------------------------------------------------------------------------

ApplicationContext实现也允许容器外用户创建的已存在对象的注册,以作为bean元数据定义的补充。

通过getBeanFactory()返回BeanFactory的实现类DefaultListableBeanFactory,我们可以操作ApplicationContext的BeanFactory。

DefaultListableBeanFactory通过方法registerSingleton(..)和registerBeanDefinition(..)类支持这种注册。

但是,一般应用只通过元数据定义bean的方式工作。




bean命名

每一个bean都可以有一个或多个标识符,这些标识符在持有这些beans的容器中必须是唯一的。一个bean通常只有一个标识符,但如果需要更多,其余的可以认为是别名。

 

在基于xml配置的元数据中,我们使用id/name属性定义bean标识符。Id属性定义唯一标识符,一般这些命名是字符数字式的(‘myBean’、’fooService’等),同时也可以包含特殊字符。如果你想定义别名,可以使用name属性定义,多个别名使用逗号(,)、分号(;)或空格间隔开。

 

给bean定义id/name属性并不是必须的。如果没有id/name,容器会为bean生成一个唯一标识符。但是如果你想通过标识符引用的方式使用ref元素或服务定位,你必须提供一个标识符。一般当我们使用内部bean或者自动匹配时,不提供标识符。

 

 

在bean定义外定义别名

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


bean实例化

Bean定义本质上是创建对象的规则。容器在需要时查看规则,并使用配置元数据来创建或获取实际对象

如果我们通过基于xml的元数据配置,我们通过<bean/>元素的class属性定义对象的类型。该class属性,对应BeanDefinition实例的Class属性,一般是强制的。


使用构造函数实例化

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

使用静态工厂方法实例化

<bean id="clientService"  class="examples.ClientService"  factory-method="createInstance"/>
public class ClientService {  private static ClientService clientService = new ClientService();  private ClientService() {}  public static ClientService createInstance() {    return clientService;  }}

通过某个实例的工厂方法实例化

<!-- 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();  private DefaultServiceLocator() {}  public ClientService createClientServiceInstance() {    return clientService;  }}






0 0
原创粉丝点击