Spring实例化Bean的三种方法

  • 内容
  • 评论
  • 相关

在面向对象的程序中,要想调用某个类的成员方法,就需要先实例化该类的对象。在 Spring 中,实例化 Bean 有三种方式,分别是构造器实例化、静态工厂方式实例化和实例工厂方式实例化。本节将针对这三种方式分别进行讲解。

构造器实例化

构造器实例化是指 Spring 容器通过 Bean 对应的类中默认的构造函数实例化 Bean。下面通过案例演示如何使用构造器实例化 Bean。

1. 创建项目并导入 JAR 包

在 MyEclipse 中创建一个名称为 springDemo02 的 Web 项目,然后将 Spring 支持和依赖的 JAR 包复制到项目的 lib 目录中,并发布到类路径下。

2. 创建实体类

在项目的 src 目录下创建一个名为 com.mengma.instance.constructor 的包,在该包下创建一个实体类 Person1,如下所示。

package com.mengma.instance.constructor;
public class Person1 {
}

3. 创建 Spring 配置文件

在 com.mengma.instance.constructor 包下创建 Spring 的配置文件 applicationContext.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" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <bean id="person1" class="com.mengma.instance.constructor.Person1" />
</beans>

在上述配置中,定义了一个 id 为 person1 的 Bean,其中 class 属性指定了其对应的类为 Person1。

4. 创建测试类

在 com.mengma.instance.constructor 包下创建一个名为 InstanceTest1 的测试类,编辑后如下所示。

package com.mengma.instance.constructor;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InstanceTest1 {
    @Test
    public void test() {
        // 定义Spring配置文件的路径
        String xmlPath = "com/mengma/instance/constructor/ApplicationContext.xml";
        // 初始化Spring容器,加载配置文件,并对bean进行实例化
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        // 通过容器获取id为person1的实例
        System.out.println(applicationContext.getBean("person1"));
    }
}

上述文件中,首先在 test() 方法中定义了 Spring 配置文件的路径,然后 Spring 容器会加载配置文件。在加载的同时,Spring 容器会通过实现类 Person1 中默认的无参构造函数对 Bean 进行实例化。

5. 运行程序并查看结果

使用 JUnit 测试运行 test() 方法,运行成功后,控制台的输出结果如图 1 所示。

输出结果
图 1  输出结果

本文标题:Spring实例化Bean的三种方法

本文地址:https://www.hosteonscn.com/5832.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注