Spring5源码 - BeanFactory、FactoryBean

本文详细介绍了Spring中的BeanFactory和ApplicationContext容器,解释了FactoryBean的概念及其使用方式,包括通过工厂方法创建Bean实例。同时,文章讨论了Spring容器的层次结构,如AutowireCapableBeanFactory和ConfigurableListableBeanFactory,以及DefaultListableBeanFactory作为实际的IoC容器的角色。此外,还提到了组件扫描和自动装配的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BeanFactory是SpringBean容器的根接口,定义了Bean工厂的最基本的特性,生成的类都是有此接口的实现类来管理的。

FactoryBean 的本质也是一个Bean,用于生成普通的Bean,初始化时,会把这个接口的Bean给取出来,通过其中getObject() 方法来生成我们想要的bean。

在spring的xml配置文件中可以通过以下方式来创建实例:

public class User {}

public class UserFactory {
    // 普通方法返回User对象,不能通过类名调用,需要通过对象调用
    public User getUser() {
        return new User();
    }
}
<bean id="userFactory" class="com.demo.entity.UserFactory"/> <!-- 创建userFactory实例(bean) -->
<bean id="user" factory-bean="userFactory" factory-method="getUser" scope="singleton"/>

此种创建bean实例的方式并不是真正通过FactoryBean来创建的,因为这里是通过userFactory实例(factory-bean)中的getUser方法(factory-method) 来创建出来的user实例。

通过实现FactotyBean接口来创建User实例:

public class UserFactoryBean implements FactoryBean<User> {
    @Override
    public User getObject() throws Exception {
        return new User();
    }

    @Override
    public Class<User> getObjectType() {
        return User.class;
    }
}

载入IOC容器:

<!-- 创建userFactoryBean实例(bean)-->
<bean id="userFactoryBean" class="com.demo.entity.UserFactoryBean"/> 

调用测试,发现是能够通过FactoryBean来创建Bean的

public static void test1() {
    String xmlPath = "classpath:spring/spring-beans.xml";
    ApplicationContext context = new FileSystemXmlApplicationContext(xmlPath);

    User user = (User) context.getBean("userFactoryBean");
    System.out.printf("factoryBean创建的实例:%s",user);
}

如果要获取FactoryBean,而不是实现的getObject() 方法所返回的实例,那么就需要使用BeanFactory接口中的:

public interface BeanFactory {
	/**
	 * Used to dereference a {@link FactoryBean} instance and distinguish it from
	 * beans <i>created</i> by the FactoryBean. For example, if the bean named
	 * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
	 * will return the factory, not the instance returned by the factory.
	 */
	String FACTORY_BEAN_PREFIX = "&";
}

在 FactoryBean 的实现类名前加个&作用符,用于获取factoryBean而不是获取其中getObject() 创建的bean。

public static void test1() {
    String xmlPath = "classpath:spring/spring-beans.xml";
    ApplicationContext context = new FileSystemXmlApplicationContext(xmlPath);

  	UserFactoryBean userFactoryBean = (UserFactoryBean) context.getBean("&userFactoryBean");
  	System.out.printf("factoryBean===> %s", userFactoryBean);
}

Spring的设计主要分为两个路线:

  • 以BeanFactory接口为主的简单容器
  • 以ApplicationContext接口为主的高级核心容器,也就是我们广泛使用的容器

接口的定义均符合单一职责。
在这里插入图片描述
ListAbleBeanFactory 接口可以批量的获取Bean相关信息,例如经常使用的方法 String[ ] getBeanDefinitionNames() 就是来自该接口的定义。

组件扫描与自动装配

组件扫描:自动发现应用容器中需要创建的Bean

自动装配:自动满足Bean之间的依赖

BeanFactory 的子类如下:
在这里插入图片描述

AutowireCapableBeanFactory

该接口定义了用于填充那些不受Spring容器控制的类。

/** 
 * <p>Integration code for other frameworks can leverage this interface to
 * wire and populate existing bean instances that Spring does not control
 * the lifecycle of. This is particularly useful for WebWork Actions and
 * Tapestry Page objects, for example.
 */
public interface AutowireCapableBeanFactory extends BeanFactory { ... }

装配的方法主要是其实现类中 AbstractAutowireCapableBeanFactory 的 autowireBean(Object) 方法中调用的 populateBean() 方法:

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory { 
	@Override
	public void autowireBean(Object existingBean) {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		initBeanWrapper(bw);
         // Populate the bean instance in the given BeanWrapper with the property values 
         // from the bean definition.
		populateBean(bd.getBeanClass().getName(), bd, bw);
	}
}

在代码中,不建议直接使用 AutowireCapableBeanFactory 接口,建议使用 @Autowired 装配。

ConfigurableListableBeanFactory

该接口继承了BeanFactory体系的其它接口,包含了BeanFactory体系的所有方法。

public interface ConfigurableListableBeanFactory
		extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {...}

DefaultListableBeanFactory

该类是真正的第一个可以独立运行的IoC容器。

/**
 * 继承了AbstractAutowireCapableBeanFactory抽象类,
 * 不仅实现了ConfigurableListableBeanFactory接口还实现了BeanDefinitionRegistry
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {...}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值