Spring实例化方式(源码解读)

概述

这篇文章主要是举例说明实例化Bean的不同方式,大致分为构造函数实例化、静态工厂方法实例化、实例工厂方法实例化。然后通过源码分析底层是怎么实现的。

案例

XML配置Bean

public class QueueService {

	private static QueueService queueService = new QueueService();

	public static QueueService getInstance(){
		return queueService;
	}
	public void say(){
		System.out.println("6号队列");
	}

}
public class InstantFactory {

	private static AreaService areaService = new AreaService();

	public AreaService createAreaService(){
		return areaService;
	}
}
public class AreaService {

	public void say(){
		System.out.println("6号诊区");
	}
}
public class CorpService {


	public void say(){
		System.out.println("6号院区");
	}
}

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		//用构造函数实例化
		CorpService corpService = (CorpService)ac.getBean("corpService");
		corpService.say();
		//使用静态工厂方法实例化
		QueueService queueService = (QueueService)ac.getBean("queueService");
		queueService.say();
		//使用实例工厂方法实例化
		AreaService areaService = (AreaService)ac.getBean("areaService");
		areaService.say();
	}
	<?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">
	<bean id="corpService" class="com.test.instant.CorpService"/>
	<!--静态工厂实例化Bean-->
	<bean id="queueService" class="com.test.instant.QueueService" factory-method="getInstance"/>
	<!--实例工厂实例化Bean-->
	<bean id="instant" class="com.test.instant.InstantFactory"/>
	<bean id="areaService" factory-bean="instant" factory-method="createAreaService"/>
</beans>

说明

  • 使用静态工厂方法实例化:定义使用静态工厂方法创建的 bean 时,请使用class属性来指定包含static工厂方法的类,并使用名为factory-method的属性来指定工厂方法本身的名称。您应该能够调用此方法(带有可选参数,如稍后所述)并返回一个活动对象,该对象随后将被视为已通过构造函数创建。这种 bean 定义的一种用法是在旧代码中调用static工厂。
  • 使用实例工厂方法实例化:使用实例工厂方法实例化从容器中调用现有 bean 的非静态方法以创建新 bean。要使用此机制,请将class属性留空,并在factory-bean属性中,在当前(或父容器或祖先容器)中指定包含要创建该对象的实例方法的 bean 的名称。使用factory-method属性设置工厂方法本身的名称

源码分析

实例化的源码主要在AbstractAutowireCapableBeanFactory类的createBeanInstance方法中

	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}
	
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		if (mbd.getFactoryMethodName() != null) {
			//静态工厂、实例工厂实例化方法
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// 4.下面这段代码都是在通过构造函数实例化这个Bean,分两种情况,一种是通过默认的无参构造,一种是通过推断出来的构造函数
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		//无参构造器实例化
		return instantiateBean(beanName, mbd);
	}

下面是归纳了,不同的场景下走的不同的方法,除了用xml来实例化Bean外,还有我们常用的注解的方式来实例化Bean。

instantiateUsingFactoryMethodinstantiateBean
静态工厂实例化构造函数实例化
实例工厂实例化@Service、@component
@Bean@Configuration
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值