Spring实例化过程几种方式以及构造器的选择

一、bean实例化几种方式

  1. 实例化前调用postProcessBeforeInstantiation后置处理器接口(自定义对象返回)
  2. 通过supplier方式创建supplier不需要通过反射,而是在supplierFactory中直接实例化对象,所以supplier的效率比其他方式要高
  3. 通过工程方法、静态方法形式创建类似@Bean
  4. 通过构造器的形式实例化(多个构造器混存在选择)
  5. 其他方式(@Lazy\Lookup\replace-method)等

二、实例

1、自定义后置处理器

@Component
public class MyMegerdPostProcessor implements InstantiationAwareBeanPostProcessor {

   public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return new UserService();
    }
}

源码部分

        1//AbstractAutowireCapableBeanFactory#createBean(java.lang.String, RootBeanDefinition, Object[])调用后置处理器
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
  
      
2protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
				   //实例化前调用
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}

2、通过supplier方法形式
个人感觉spring这样设计感觉考虑到效率层面,supplier不需要通过反射,而是在supplierFactory中直接实例化对象,所以supplier的效率比其他方式要高。可以一般在xml配置supplier

public class SupplierTest {
	public Object instanceObject(){
		return new UserService();
	}

}	

@Test
	public void staticsModel(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

		context.register(ObjectFactory.class);
		GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
		beanDefinition.setBeanClass(UserService.class);
		beanDefinition.setFactoryBeanName("SupplierTest");
		beanDefinition.setFactoryMethodName("instanceObject");
    
		context.registerBeanDefinition("a", beanDefinition);
		context.refresh();

	}


优先级:postProcessBeforeInstantiation>instanceSupplier >@Bean>构造器

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());
		}
		//1、调用设置的instanceSupplier 
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}
		//2、调用工程方法、静态方法@Bean的形式
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		//3存在多个构造器选择
		// 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);
		}

		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}

3、@Bean形式、工程方法形式比较简单

4、构造器的选择
当存在多个构造方法、多个构造方法存在@Autowired注解有没有考虑过该选择那个呢

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        //省略部分代码
		// Candidate constructors for autowiring?
		//1、把类中所有构造器找出,找出的结果下图
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		//2、根据ctos值
		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);
		}

		// No special handling: simply use no-arg constructor.
		//使用默认构造器无参
		return instantiateBean(beanName, mbd);
	}

determineConstructorsFromBeanPostProcessors(beanClass, beanName);中找出的方法
Spring实例化过程几种方式以及构造器的选择_第1张图片

待补充

你可能感兴趣的:(Spring,spring)