Spring生成bean的过程
spring是java程序员的春天,很多人写完helloworld后就转入了spring的怀抱。现在来了解一下bean是怎么创建的吧。
这里假设你已经对java比较了解,类反射代理之类的也有所涉猎。否则建议先了解一下类的反射。
如何定义Bean
假设你在写一个类Dog,Dog有年龄age,名字name,它还可以say。以下是实现代码:
public class Dog {
public Integer age;
public String name;
public void say(){
System.out.println("my name is "+name+" . age is "+age);
}
public static void main(String[] args) {
new Dog().say();
}
}
我们来看看怎么描述我们想要创建的Dog。
类名
类名肯定得有,到时候通过Class#forName()
方法可以加载到这个类。
实例别名
如果你不想通过类名来描述一个实例,又或是这个类有多个实例,这时候就需要一个实例别名来描述了。
构造函数
如果你希望通过向特定的构造函数传入入参来创建实例,那么你得描述到底使用哪个构造函数,简单的可以通过每个参数的类型,来判断。然而,如果你的入参是通过别的bean定义得来的,那你可得考虑两个实例的生成关系了。
属性设置
就像这个Dog类,不用向构造函数传参即可new出来,那如果想在实例生成后设置上属性该怎么做呢?是不是得标记一下你想给哪个属性设置什么值。
初始化方法
你的实例生成了,属性也设置上了,你想让他试着叫一下,是不是得指定say方法在实例化后执行?
销毁方法
假如你的Dog连接了一些资源,在下线时需要销毁,是不是得指定方法在系统执行完后执行?
其他方面,读者可以再考虑一下。
BeanDefinition
在第一小节中,大家大致了解了对于一个对象该怎么描述。为什么需要考虑对象的描述呢?因为使用spring就会把对象的生成交给spring,spring需要知道对象该怎么生成。
在spring中,BeanDefinition就是描述对象的类。在getBean时,spring通过对BeanDefinition列表的扫描得知你需要哪一个bean,进而生成bean返回给你。
通过代码生成BeanDefinition
最普通的情况就是通过xml生成了,spring通过对xml的读取解析得到用户写的bean配置,想一想第一小节中那些描述点都在spring的xml配置的哪些地方。
实际上也可以通过代码生成:
public class Dog {
public Integer age;
public String name;
public void say(){
System.out.println("my name is "+name+" . age is "+age);
}
public void setAge(Integer age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
new Dog().say();
// 准备生成dog的定义
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(Dog.class);
// 设置它的属性
builder.addPropertyValue("name","john");
builder.addPropertyValue("age",1);
// 生成beanFactory
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 添加dog定义
beanFactory.registerBeanDefinition("dog",builder.getBeanDefinition());
// 获取dog
Dog dog = (Dog) beanFactory.getBean("dog");
dog.say();
}
}
结果如下:
my name is null . age is null
my name is john . age is 1
通过xml生成BeanDefinition
xml生成BeanDefinition无非是原先用代码描述的BeanDefinition换成用xml描述,至于怎么读取xml,spring有自己的方法。而xml的解析技术一般分为两种 DOM SAX
DOM方式
根据XML的层级结构在内存中分配一个树形结构,把XML的标签,属性和文本等元素都封装成树的节点对象
- 优点: 便于实现增 删 改 查
- 缺点: XML文件过大可能造成内存溢出
SAX方式
采用事件驱动模型边读边解析:从上到下一行行解析,解析到某一元素, 调用相应解析方法
- 优点: 不会造成内存溢出,
- 缺点: 查询不方便,但不能实现 增 删 改
具体如何解析这里就不深究了,重点是你可以从xml节点上读取相关信息生成BeanDefinition
实际使用
实际上,DefaultListableBeanFactory不具备从xml配置中获取BeanDefinition,它只能通过代码的方式注册。我们应用一般采用ApplicationContext
的实现类FileSystemXmlApplicationContext
,ClassPathXmlApplicationContext
和WebXmlApplicationContext
来从xml中获取BeanDefinition,并注册到自身的属性BeanFactory中。ClassPathXmlApplicationContext的类关系图如下:
在生成ClassPathXmlApplicationContext
对象时,构造函数入参会传入具体xml配置文件的位置,可以是单个,也可以是多个,也可以包含匹配符。
接着会调用AbstractApplicationContext
的refresh方法。refresh方法中会调用自身方法obtainFreshBeanFactory来获取生成的Bean。
obtainFreshBeanFactory方法会调用AbstractRefreshableApplicationContext
的refreshBeanFactory方法。这个方法的作用是销毁已有beanFactory中的bean,并且关闭beanFactory。接着会去生成一个DefaultListableBeanFactory对象,最后使用loadBeanDefinitions方法从xml配置中加载BeanDefinition。
实际上AbstractXmlApplicationContext
实现了loadBeanDefinitions方法,在这个方法里,使用了XmlBeanDefinitionReader对象来读取xml配置信息并转换成BeanDefinition。XmlBeanDefinitionReader采用SAX方式读取xml。
生成Bean对象
上边两个小节描述了Bean的定义,接下来就是重头了,如何生成Bean对象,spring又是如何让生成Bean对象变得可扩展。
使用反射技术生成对象
public class Dog {
protected Integer age;
public String name;
public void say(){
System.out.println("my name is "+name+" . age is "+age);
}
public void setAge(Integer age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
try {
// 获取Dog类
Class dogClass = Class.forName("Dog");
// 通过类生成对象
Dog dog1 = (Dog) dogClass.newInstance();
// 获取特定的属性
Field field = dogClass.getField("name");
// 填充属性
field.set(dog1,"landa");
dog1.say();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
结果:
my name is landa . age is null
以上代码演示了如何不通过new的方式生成对象,并且给对象设置上属性值。可以说,spring做的一切都是基于java的反射。
BeanFactory类图
AbstractBeanFactory#doGetBean方法
DefaultListableBeanFactory的getBean方法最终会调用AbstractBeanFactory的doGetBean方法。
doGetBean方法执行流程:
doGetBean方法:
protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
AbstractAutowireCapableBeanFactory#createBean方法
createBean方法执行流程:
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
AbstractAutowireCapableBeanFactory#doCreateBean方法
doCreateBean方法执行流程:
循环依赖且带代理的情况
注意其流程,这里举一个例子,C和D类循环依赖,且C和D类会被代理。
- 先准备创建C,C实现类被称为元对象c
- 元对象c被放入被放入singletonFactories,且调用的是getEarlyBeanReference方法(这个方法比较凶残,会调用SmartInstantiationAwareBeanPostProcessor实现类的getEarlyBeanReference方法传入元返回新对象,AbstractAutoProxyCreator是该接口的实现类,他真正实现了生成代理)
- 执行populateBean方法给元对象c赋值
- 好戏来了,这时候需要获取创建的D,元对象d也走上述方法。
- 到populateBean方法赋值时,doGetBean方法会把处在singletonFactories的对象c通过调用getEarlyBeanReference方法生成代理对象c,并且推到earlySingletonObjects中。
- 也就是说元对象d拿到的是代理对象c,但此时代理对象c中的元对象c里并没有d,如果在d初始化方法中调用c对象中的d的方法,那铁定报错。
- 调用元对象d的初始化方法
- 此时元对象d并没有在earlySingletonObjects中
- 注册元对象d回调,
- 正式生成单例对象d->调用getEarlyBeanReference方法生成代理对象d,并放入最终的singletonObjects中
- 元对象c的populate方法可以执行了,初始化方法也可以执行了。
- 此时元对象c在earlySingletonObjects中
- 正式生成单例对象c->调用getEarlyBeanReference方法生成代理对象c,并放入最终的singletonObjects中
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
AbstractAutowireCapableBeanFactory#createBeanInstance方法
createBeanInstance方法执行流程
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, 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());
}
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);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.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);
}
AbstractAutowireCapableBeanFactory#populateBean方法
populateBean方法执行流程:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs);
}
AbstractAutowireCapableBeanFactory#initializeBean方法
initializeBean方法执行流程:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}