public class XmlMain { public static void main(String[] args) throws Exception { XmlMain xmlMain = new XmlMain(); //解析xml,获取bean定义 Map map = xmlMain.parseXml(); //student的定义 BeanDefinition studentDefinition = map.get("student"); //生成student对象 Object object = xmlMain.loadBean(studentDefinition); //设置student对象属性 xmlMain.setProperty(object, studentDefinition); //使用student Student student = (Student) object; student.print(); } /** * 解析bean * * @return key->beanName,value->bean的定义 * @throws Exception */ public Map parseXml() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = ResourceUtils.getFile("classpath:parseTest.xml"); //读取配置文件 Document d = builder.parse(file); //获取所有bean节点 NodeList nodeList = d.getElementsByTagName(BeanDefinitionParserDelegate.BEAN_ELEMENT); Map map = new HashMap (); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; //解析节点属性 String id = element.getAttribute(BeanDefinitionParserDelegate.ID_ATTRIBUTE); String className = element.getAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE); AbstractBeanDefinition beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition( null, className, null); NodeList childrenList = element.getChildNodes(); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); for (int j = 0; j < childrenList.getLength(); j++) { Node children = childrenList.item(j); if (children.getNodeType() == Node.ELEMENT_NODE) { //解析子property节点 Element childrenElement = (Element) children; String name = childrenElement.getAttribute(BeanDefinitionParserDelegate.NAME_ATTRIBUTE); String value = childrenElement.getAttribute(BeanDefinitionParserDelegate.VALUE_ATTRIBUTE); mutablePropertyValues.add(name, value); } } beanDefinition.setPropertyValues(mutablePropertyValues); map.put(id, beanDefinition); } } return map; } /** * 创建bean * * @param beanDefinition * @return * @throws Exception */ public Object loadBean(BeanDefinition beanDefinition) throws Exception { Class clazz = Class.forName(beanDefinition.getBeanClassName()); Constructor constructorToUse; //获取默认构造方法 constructorToUse = clazz.getDeclaredConstructor(); return constructorToUse.newInstance(); } /** * 属性赋值,spring的远比这个复杂 * * @param object * @param beanDefinition * @return * @throws Exception */ public Object setProperty(Object object, BeanDefinition beanDefinition) throws Exception { MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues(); //获取obj类的字节文件对象 Class c = object.getClass(); List list = mutablePropertyValues.getPropertyValueList(); for (PropertyValue x : list) { //获取该类的成员变量 Field f = c.getDeclaredField(x.getName()); //取消语言访问检查 f.setAccessible(true); //给变量赋值 f.set(object, x.getValue()); } return object; }}
看完大概就知道什么意思了,对于理解spring很重要,下面开始吧。
例子
这里讲一个最最简单的例子,用来引出本文。
依赖
org.springframework spring-context 4.3.11.RELEASE
配置文件
这里定义了一个很简单的bean,这个类的代码就不贴了。
启动spring
public class Main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml"); HelloService helloService = applicationContext.getBean(HelloService.class); System.out.println(helloService.hello("占旭鹏")); }}
public void setConfigLocations(String... locations) { if (locations != null) { Assert.noNullElements(locations, "Config locations must not be null"); this.configLocations = new String[locations.length]; for (int i = 0; i < locations.length; i++) { this.configLocations[i] = resolvePath(locations[i]).trim(); } } else { this.configLocations = null; } }
protected String parseStringValue( String value, PlaceholderResolver placeholderResolver, Set visitedPlaceholders) { StringBuilder result = new StringBuilder(value); //placeholderPrefix为${,找到${的位置 int startIndex = value.indexOf(this.placeholderPrefix); while (startIndex != -1) { //找到}的位置 int endIndex = findPlaceholderEndIndex(result, startIndex); if (endIndex != -1) { //获取${}之间的内容 String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. //这里递推了一下,主要是防止占位符多层嵌套 placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); // Now obtain the value for the fully resolved key... //根据key从环境变量中获取值。 String propVal = placeholderResolver.resolvePlaceholder(placeholder); if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. //这里防止获取到的值中包含占位符,又递归了一下 propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders); //占位符替换 result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); if (logger.isTraceEnabled()) { logger.trace("Resolved placeholder '" + placeholder + "'"); } startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'" + " in value \"" + value + "\""); } visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1; } } //返回替换后的值 return result.toString(); }
我们再回到原来的方法。下面我们重点看一下refresh方法。
@Override public void refresh() throws BeansException, IllegalStateException { //防止"refresh"、"destroy"存在并发操作。 synchronized (this.startupShutdownMonitor) { // 刷新前的准备工作,下面会讲 prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
下面讲一下prepareRefresh,里面主要是设置了一下变量,做了一个校验,具体代码如下
protected void prepareRefresh() { //设置启动时间 this.startupDate = System.currentTimeMillis(); //设置启动变量 this.closed.set(false); this.active.set(true); if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); } // 钩子,给子类继承,实际没有用到 initPropertySources(); // 校验必配的环境变量有没有配置,下面会具体讲下 getEnvironment().validateRequiredProperties(); // Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet (); }
校验环境变量有没有配置,这个方法很简单,就是遍历一下,然后判断值是否存在,不存在记录异常。
public void validateRequiredProperties() { MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException(); for (String key : this.requiredProperties) { if (this.getProperty(key) == null) { ex.addMissingRequiredProperty(key); } } if (!ex.getMissingRequiredProperties().isEmpty()) { throw ex; } }
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { if (this.allowBeanDefinitionOverriding != null) { beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } if (this.allowCircularReferences != null) { beanFactory.setAllowCircularReferences(this.allowCircularReferences); } }
重点方法是loadBeanDefinitions,里面是解析bean的过程。
@Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); //重点 loadBeanDefinitions(beanDefinitionReader); }
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException { Assert.notNull(locations, "Location array must not be null"); int counter = 0; for (String location : locations) { //下面会讲 counter += loadBeanDefinitions(location); } //返回总共加载的bean的数量 return counter; }
protected void resetBeanDefinition(String beanName) { // Remove the merged bean definition for the given bean, if already created. clearMergedBeanDefinition(beanName); // Remove corresponding bean from singleton cache, if any. Shouldn't usually // be necessary, rather just meant for overriding a context's default beans // (e.g. the default StaticMessageSource in a StaticApplicationContext). destroySingleton(beanName); // Reset all bean definitions that have the given bean as parent (recursively). for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } } } }
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable { //保存所有的BeanDefinition private final Map beanDefinitionMap = new ConcurrentHashMap (256); //保存的beanName private volatile List beanDefinitionNames = new ArrayList (256); }
@Override public void refresh() throws BeansException, IllegalStateException { //防止"refresh"、"destroy"存在并发操作。 synchronized (this.startupShutdownMonitor) { // 刷新前的准备工作 prepareRefresh(); // 解析beanDefinition,注册beanDefinition. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean prepareBeanFactory(beanFactory); try { // 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor postProcessBeanFactory(beanFactory); // 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法 invokeBeanFactoryPostProcessors(beanFactory); // 注册继承了BeanPostProcessor接口的bean,下面重点讲这个 registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
registerBeanPostProcessors方法
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { //获取继承了BeanPostProcessor的bean String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; //这里又注册了一个BeanPostProcessor beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. //继承自PriorityOrdered的 List priorityOrderedPostProcessors = new ArrayList (); //继承自MergedBeanDefinitionPostProcessor的 List internalPostProcessors = new ArrayList (); //继承自Ordered的 List orderedPostProcessorNames = new ArrayList (); //仅仅继承自BeanPostProcessor的 List nonOrderedPostProcessorNames = new ArrayList (); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } //排序注册 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. //获取继承自Ordered的 List orderedPostProcessors = new ArrayList (); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //排序注册 sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // 获取仅仅继承自BeanPostProcessor的 List nonOrderedPostProcessors = new ArrayList (); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //注册 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // 排序注册 sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); //这里注册了一个特殊的BeanPostProcessor beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
这里就是注册一下,没有实际执行。
下面继续看refresh方法
@Override public void refresh() throws BeansException, IllegalStateException { //防止"refresh"、"destroy"存在并发操作。 synchronized (this.startupShutdownMonitor) { // 刷新前的准备工作 prepareRefresh(); // 解析beanDefinition,注册beanDefinition. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean prepareBeanFactory(beanFactory); try { // 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor postProcessBeanFactory(beanFactory); // 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法 invokeBeanFactoryPostProcessors(beanFactory); // 注册继承了BeanPostProcessor接口的bean registerBeanPostProcessors(beanFactory); // 这个是信息国际化,跳过 initMessageSource(); // 初始化当前ApplicationContext的事件广播器,先跳过 initApplicationEventMulticaster(); // 这个方法是提供给子类实现的,暂时没有用到 onRefresh(); // 注册事件监听器,监听器需要实现ApplicationListener接口。先跳过。 registerListeners(); // 这里初始化所有不是懒加载的单例bean,下面会重点讲 finishBeanFactoryInitialization(beanFactory); // 完成刷新,也先跳过 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
finishBeanFactoryInitialization方法
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { //不包含,跳过 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } //先不讲,跳过 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { return getEnvironment().resolvePlaceholders(strVal); } }); } //这是AspectJ相关的内容,先跳过 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null); //spring开始预初始化singleton beans了,这个时候不能出现bean定义解析、加载、注册 beanFactory.freezeConfiguration(); //开始初始化,这是重点,下面讲 beanFactory.preInstantiateSingletons(); }
preInstantiateSingletons方法
@Override public void preInstantiateSingletons() throws BeansException { if (logger.isDebugEnabled()) { logger.debug("Pre-instantiating singletons in " + this); } //this.beanDefinitionNames保存了所有的beanNames List beanNames = new ArrayList (this.beanDefinitionNames); //触发所有的非懒加载的singleton beans的初始化操作 for (String beanName : beanNames) { //合并父Bean中的配置,注意 中的parent,下面会重点讲一下 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //非抽象的、singleton,并且是非懒加载的,才会初始化 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //处理FactoryBean if (isFactoryBean(beanName)) { //FactoryBean的话,在beanName前面加上'&'符号,再调用getBean final FactoryBean factory = (FactoryBean ) getBean(FACTORY_BEAN_PREFIX + beanName); //判断当前FactoryBean是否是SmartFactoryBean的实现 boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction () { @Override public Boolean run() { return ((SmartFactoryBean ) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean ) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { //对于普通的Bean,只要调用getBean(beanName)这个方法就可以进行初始化了 getBean(beanName); } } } //到这里说明所有的singleton beans已经完成了初始化 //如果我们定义的bean是实现了SmartInitializingSingleton接口的,那么在这里得到回调 // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction
public class MySmartInitializingSingleton implements SmartInitializingSingleton { public void afterSingletonsInstantiated() { System.out.println("单例所有初始化完成执行。。。"); }}
public Object getSingleton(String beanName, ObjectFactory singletonFactory) { Assert.notNull(beanName, "'beanName' must not be null"); synchronized (this.singletonObjects) { //如果已经创建了直接返回 Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); } //创建之前加一条记录,表示正在创建 beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet (); } try { singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. //如果发生异常考虑是并发的情况,重新获取一下实例,如果获取到就当创建成功。 singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } //创建成功,移除正在创建记录 afterSingletonCreation(beanName); } //如果是新创建的bean,这里需要保存一下实例 if (newSingleton) { addSingleton(beanName, singletonObject); } } return (singletonObject != NULL_OBJECT ? singletonObject : null); } }
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //说明不是FactoryBean,这里实例化Bean,下面会讲 instanceWrapper = createBeanInstance(beanName, mbd, args); } //获取实例 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); //类型 Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; //MergedBeanDefinitionPostProcessor,先跳过 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } //下面这块代码是为了解决循环依赖的问题,先跳过 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() { @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) { //这里处理bean初始化完成后的各种调用,比如init-method方法,InitializingBean接口,BeanPostProcessor接口 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 actualDependentBeans = new LinkedHashSet (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; }
createBeanInstance方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { // Make sure bean class is actually resolved at this point. //确保已经加载了此class,如果没有加载,则加载 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); } //如果不是第一次创建,比如第二次创建prototype 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); }