spring实例化-构造函数实例化

spring实例化分为构造函数实例化和静态工厂实例化;当我们没有指定具体的实例化方式时,默认采用无参的构造函数实例化。
一:bean,xml

<bean id="userService" class="service.UserService">
		<property name="map">
			<map>
				<entry key="name" value="test"/>
				<entry key="age" value="20"/>
			</map>
		</property>
		<property name="userDto" ref="userDto"></property>
	</bean>

二:测试类

public class UserService {

	/*public UserService(String name){
		System.out.println("进入有参构造函数。。。。。。。。。。。。。。。。。。");
	}*/

	private UserDto userDto;

	private Map<String,String> map;

	public UserDto getUserDto() {
		return userDto;
	}

	public void setUserDto(UserDto userDto) {
		this.userDto = userDto;
	}

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}


}

通过main方法,进入源码看下具体的实例化流程

public static void main(String[] args) {
		//1.资源定位
		Resource resource = new ClassPathResource("bean.xml");
		//2.创建IOC容器,这里使用DefaultListableBeanFactory作为IOC容器
		DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory();
		//3.读取BeanDefinition并注册到IOC容器中
		BeanDefinitionReader reader = new XmlBeanDefinitionReader(defaultListableBeanFactory);
		reader.loadBeanDefinitions(resource);

		//从容器中获取对象
		UserService userService = (UserService) defaultListableBeanFactory.getBean("userService");

	}

getBean方法是IOC容器实例化的开始的地方,包括依赖注入,通过getBean方法一路跟踪,可以看到bean实例化的具体流程;
通过getBean——》doGetBean——》getSingleton——》createBean——》doCreateBean——》createBeanInstance  在这里插入图片描述

具体实例化通过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);
		}

		// 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;
				}
			}
		}
		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);
		}

		// No special handling: simply use no-arg constructor.
		//使用默认的构造函数进行实例化
		return instantiateBean(beanName, mbd);
	}

调用instantiateBean在这里插入图片描述
调用InstantiationStrategy的instantiate方法,instantiate方法是接口,由实现类SimpleInstantiationStrategy完成实例化
在这里插入图片描述

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		if (!bd.hasMethodOverrides()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
				//取得指定的构造器或者生成对象工厂方法来对bean进行实例化
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					//获取bean的Class
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
						//如果Class是接口,则抛出异常
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(
									(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
						}
						else {
							//通过Class获取无参构造器
							constructorToUse = clazz.getDeclaredConstructor();
						}
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			//通过BeanUtils进行实例化
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			//使用CGLIB实例化对象
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}

通过BeanUtils.instantiateClass进行实例化
在这里插入图片描述
通过构造器的newInstance方法实例化,并将实例化的结果返回,并进行属性注入等后续操作

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
		Assert.notNull(ctor, "Constructor must not be null");
		try {
			ReflectionUtils.makeAccessible(ctor);
			//通过反射实例化
			return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
					KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
		}
		catch (InstantiationException ex) {
			throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
		}
		catch (IllegalAccessException ex) {
			throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
		}
		catch (IllegalArgumentException ex) {
			throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
		}
		catch (InvocationTargetException ex) {
			throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值