Spring基础一:容器和Bean

前言

这个系列的文章,以Spring5.*的官方文档为蓝本,经过翻译、整理和简化而成,没有添加任何其他来源的内容。因此,内容的正确性是有保证的;不好的地方是,由于本人功力有限,翻译整理后的文字流畅性不是很好。另一方面,Spring的官方文档,本身就不具备深入浅出、实例丰富的特点,本人写作的时候也就不提更高的要求了;但对于一些有疑问的点,还是通过实例代码稍微测试了一下,这些代码放在git上,文章里面必要时会提及。

Spring官方文档地址

第一篇介绍Spring容器,基本上使用Spring的人都必然已经了解这些知识了,权当热身吧。

容器简介

Spring最基础的功能就是实现了Ioc容器,Ioc也可以叫做DI(Dependency injection)。容器管理的对象称之为bean,容器负责bean的创建、初始化、配置、装配。 Ioc体现在,bean只需声明对其他的bean的依赖,不负责创建后者,也不需要直到后者如何被创建;容器在装配过程中负责注入这些依赖。

容器如何初始化、配置并组装bean呢?它需要一份对bean的定义数据,这个数据叫做配置元数据(configuration metadata)。最新版本的Spring允许我们通过xml、java注解两种方式来提供元数据。

org.springframework.context这个package包含了容器相关的基础类和接口定义,其中接口BeanFactory定了最基本的bean管理方法,接口ApplicationContext扩展了BeanFactory,添加了AOP,MessageSource,事件机制,Context层级结构的支持。我们在应用中使用的context实例,基本都实现了ApplicationContext,在需要访问当前context的场景下,我们基本也都使用ApplicationContext这个接口。

对于非Web应用,我们一般创建ClassPathXmlApplicationContextFileSystemXmlApplicationContext类型的容器实例。顾名思义,前者从classpath加载配置文件,后者从文件系统路径加载配置文件。xml是传统的配置数据格式,我们可以在xml里面通过声明来开启对java注解配置的支持(具体方式后面会介绍)。对于web应用,不需要手动创建容器实例,Spring MVC框架会自动创建。

总之,在应用启动时,容器读入配置数据,完成对bean的初始化和装配工作,得到一个完全初始化,可提供服务的应用系统。

配置元数据

开发者通过配置元数据告诉容器如何初始化、配置和组装bean。传统上,配置元数据通过xml格式来提供,它的特点是所有配置集中在一起,容易看明白,特别适合用作示例,所以本章节及后续(在讲到注解配置之前)主要使用xml格式。

下面是一个简单的配置文件sever.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->
</beans>

顶层beans标签,包含一个或多个bean标签,每个bean标签定义一个bean,class属性指明要创建的bean对应的java类型。

另一个配置文件dao.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>

容器初始化

假设上面两个xml位于类路径下面,那么我们可以这样来创建容器:

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

我们还可以换一种方式,让server.xml来导入dao.xml,Context加载server.xml即可。

--services.xml
<beans>
	<import resource="daos.xml"/>
	<!-- services.xml自身的定义在这 -->
<beans>

注意import标签的resource属性指向的路径是services.xml所在位置的相对路径。

初始化完成之后,可以调用getBean方法来获取一个bean的实例:

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();

Bean介绍

Spring容器通过配置数据来获取bean的定义,每个bean的定义会被读取为一个BeanDefinition对象,它包含以下信息:

  1. bean对象对应的完全限定类名;
  2. 行为相关属性,比如scope,lefcycle回调等;
  3. 对其他bean的依赖引;
  4. 属性值的配置

Spring的容器实现还允许将容器外部创建的对象注册到容器里面,方法如下:

DefaultListableBeanFactory  factory = context.getBeanFactory();
factory.registerSingleton(beanName,objectInstance);

bean的命名

bean可以有一个或多个身份标识,每个标识在容器中都应该是唯一的。在xml配置中,bean的id属性可以配置单个标识,name属性可以配置逗号分隔的多个标识。

如果我们不提供任何标识定义,容器会生成一个内部唯一的标识。在xml里面,通过bean名字引用bean是很常见的,比如services.xml里面petStore的属性配置中,ref标签指向名叫dao的bean。

注1:bean的命名应该和变量命名一样,采用驼峰命名法;
注2:spring在给bean自动命名时,会尝试使用类名,并将第一个字符变成小写;但如果类名的前两个字符都是大小,那么第一个字符保持大写;如果类名是NameBean,生成的名字就是nameBean,如果类名是NAmeBean,那么生成的名字是NAameBean。

我们可以额外给bean添加别名,这往往发生在大型系统里面,A某块导入了B模块定义的bean,却想换个名字:

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

bean的创建

bean的定义可以配置3种bean的创建方式:

1、指定bean的类名,默认通过对构造函数创建,这是最常见的方式;
2、指定bean的类名,以及一个静态工厂方法:

//类定义    
public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

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

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

这个配置指示容器调用examples.ClientService.createInstance()来创建名叫clientService的bean。

3、指定bean的工厂bean,以及一个工厂方法:


//工厂类
public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

//工厂bean和bean
<bean id="serviceLocator" class="examples.DefaultServiceLocator"/>
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

上面的配置中,clientService是由另一个bean serviceLocator创建的,此时后者被称之为FactoryBean。

总结

  1. Spring的容器是用来管理bean的,包括bean的创建、bean的初始化,以及依赖注入;
  2. bean的定义和创建是完全解耦的,使得Spring很方便地支持多种bean的定义格式:xml,注解,java代码或它们的混合;
  3. 不管何种形式,bean定义在Spring内部表示为BeanDefinition数据结构;
  4. BeanDefinition是bean的元数据(相当于菜谱),容器在需要时基于元数据创建bean的实例;

这是Spring容器的核心理念,也是整个Spring技术框架体系的基石。

示例代码的container_xml模块,展示了最基本的容器功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值