2025/2/28 上午《尚硅谷》——spring中FactoryBean

一、FactoryBean 简介

FactoryBean 是 Spring 框架中的一个接口,用于创建复杂的对象并将其交给 Spring IOC 容器管理。与普通的 Bean 不同,FactoryBean 本身是一个工厂,它负责创建并返回另一个对象。通过实现 FactoryBean 接口,我们可以自定义对象的创建逻辑。

FactoryBean 接口中有三个核心方法:

  1. getObject():返回由工厂创建的对象实例。这个对象会被交给 IOC 容器管理。

  2. getObjectType():返回工厂所创建对象的类型。

  3. isSingleton():指示工厂创建的对象是否是单例的。默认返回 true,表示单例。

当我们把 FactoryBean 的实现类配置为 Spring 的 Bean 时,Spring 会调用 getObject() 方法,并将返回的对象交给 IOC 容器管理。

二、创建 UserFactoryBean 类

package com.atguigu.spring.factory;

import com.atguigu.spring.pojo.User;
import org.springframework.beans.factory.FactoryBean;

public class UserFactoryBean implements FactoryBean<User> {

    @Override
    public User getObject() throws Exception {
        // 创建一个 User 对象并返回
        return new User();
    }

    @Override
    public Class<?> getObjectType() {
        // 返回 User 类型
        return User.class;
    }
}

代码解析:

  • getObject() 方法返回一个新的 User 对象。这个对象会被 Spring IOC 容器管理。

  • getObjectType() 方法返回 User.class,表示这个工厂创建的对象类型是 User

  • 由于我们没有重写 isSingleton() 方法,默认返回 true,表示 User 对象是单例的。

三、配置 spring-factory.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.xsd">

    <!-- 配置 UserFactoryBean -->
    <bean class="com.atguigu.spring.factory.UserFactoryBean"></bean>

</beans>

配置解析:

  • 在 spring-factory.xml 中,我们配置了一个 UserFactoryBean 的 Bean。Spring 会识别这个 Bean 是一个 FactoryBean,并调用其 getObject() 方法来获取 User 对象。

四、测试 FactoryBean.java

package com.atguigu.spring.test;

import com.atguigu.spring.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FactoryBeanTest {

    @Test
    public void testFactoryBean() {
        // 获取 IOC 容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
        // 从容器中获取 User 对象
        User user = ioc.getBean(User.class);
        // 输出 User 对象
        System.out.println(user);
    }
}

测试解析:

  1. 获取 IOC 容器:通过 ClassPathXmlApplicationContext 加载 spring-factory.xml 配置文件,创建 Spring 的 IOC 容器。

  2. 获取 User 对象:通过 ioc.getBean(User.class) 从容器中获取 User 对象。由于 UserFactoryBean 已经将 User 对象交给容器管理,因此可以直接获取。

  3. 输出 User 对象:打印 User 对象的内容。由于 User 对象是刚创建且并未赋值,所以所有属性都为 null

五、输出结果

生命周期:1、创建对象
User{id=null, username='null', password='null', age=null}

输出解析:

  • User 对象被成功创建,并且所有属性都为 null,这是因为我们在 getObject() 方法中直接返回了一个新的 User 对象,没有设置任何属性。

  • 由于 UserFactoryBean 是单例的,每次从容器中获取的 User 对象都是同一个实例。