Spring4 学习笔记(3)-Spring 基于 XML 的方式配置 Bean

本小节介绍了使用 Spring 配置 Bean。

基于 XML 的配置方式:

Spring 容器介绍:

在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前,必须对它进行实例化。只有在容器实例化后,才可以从 IOC 容器里获取 Bean 实例并使用。

只有 IOC 容器初始化好了,我们才可以从中获取实例。Spring 提供了两种类型的 IOC 容器实现。
(1) BeanFactory:IOC 容器的基本实现。
BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身。
(2) ApplicationContext:提供了更多的高级特性。是 BeanFactory 的子接口。
ApplicationContext 面向使用 Spring 框架的开发者(使用者),几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
。无论使用何种方式,配置文件时都是相同的。

ApplicationContext:
ApplicationContext 的主要实现类:
(1)
ClassPathXmlApplicationContext:从 类路径下加载配置文件
(2)
FileSystemXmlApplicationContext: 从文件系统中加载配置文件
ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() 和 close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力

ApplicationContext 在初始化上下文时就实例化所有单例的 Bean(默认是单例,这个我们在讲解 bean 的作用域的时候会介绍)。

WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作

Spring4 学习笔记(3)-Spring 基于 XML 的方式配置 Bean_第1张图片

Spring4 学习笔记(3)-Spring 基于 XML 的方式配置 Bean_第2张图片
bean 的配置方法:通过全类名(即反射的方式配置)。

Spring 支持 3 种依赖注入的方式:

1、属性注入

属性注入即通过 setter 方法注入Bean 的属性值或依赖的对象。
属性注入使用 元素,使用 name 属性指定 Bean 的属性名称,value 属性或 子节点指定属性值。
属性注入是实际应用中最常用的注入方式。


<bean id="hello" class="com.liwei.spring.HelloWorld">
    <property name="name" value="老人和孩子们">property>
bean>

2、构造器注入

类文件代码片段:

package com.liwei.spring;

public class Car {
    /**
     * 公司
     */
    private String company;
    /**
     * 商标
     */
    private String brand;
    /**
     * 最大速度
     */
    private int maxSpeed;
    /**
     * 价格
     */
    private float price;

    // 此处省略了各个 Field 的 set 和 get 方法

    public Car(String company, String brand, int maxSpeed) {
        super();
        this.company = company;
        this.brand = brand;
        this.maxSpeed = maxSpeed;
    }

    public Car(String company, String brand, float price) {
        super();
        this.company = company;
        this.brand = brand;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [company=" + company + ", brand=" + brand + ", maxSpeed=" + maxSpeed + ", price=" + price + "]";
    }

}

配置文件:
提供两种方式来区分重载的构造器。
可以指定构造函数参数的顺序,也可以指定构造函数参数的类型。也可以两者结合起来使用,总之,必须让 Spring 很清楚地知道你所要得到的对象是一个具有怎样属性的对象。

<bean id="car1" class="com.liwei.spring.Car">
    <constructor-arg value="大众" index="0">constructor-arg>
    <constructor-arg value="长春一汽" index="1">constructor-arg>
    <constructor-arg value="300000" index="2">constructor-arg>
bean>

<bean id="car2" class="com.liwei.spring.Car">
    <constructor-arg value="大众" type="java.lang.String">constructor-arg>
    <constructor-arg value="长春一汽" type="java.lang.String">constructor-arg>
    <constructor-arg value="300000" type="float">constructor-arg>
bean>

通过构造方法注入Bean 的属性值或依赖的对象,它保证了 Bean 实例在实例化后就可以使用。
构造器注入在 元素里声明属性, 中没有 name 属性。
说明:可以按照参数的顺序来配置,使用属性 index 或者按照参数的类型来配置,可以使用属性 type。
使用构造器注入可以指定参数的顺序和参数的类型,以区分重载的构造器。

3、工厂方法注入(很少使用,不推荐)

你可能感兴趣的:(spring4)