
1. beanFactory
The root interface for accessing a Spring bean container.
2. BeanFactoryPostProcessor
对bean定义进行后置处理,比如jdbc类读取配置的密码,用户名等。

- public interface BeanPostProcessor {
- Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException;
-
- Object postProcessAfterInitialization(Object var1, String var2) throws BeansException;
- }
4. Enviroment接口,加载系统环境变量和属性值

5. 源码部分
- @Override
- public void refresh() throws BeansException, IllegalStateException {
- synchronized (this.startupShutdownMonitor) {
- // Prepare this context for refreshing.
- 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) {
- 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;
- }
- }
1. 创建容器obtainfreshBeanFactory,-> refreshBeanFactory. ->DefaultlistableBeanFactory,
2. 给beanFactory赋值 customizeBeanFactory
- /**
- * This implementation performs an actual refresh of this context's underlying
- * bean factory, shutting down the previous bean factory (if any) and
- * initializing a fresh bean factory for the next phase of the context's lifecycle.
- */
- @Override
- protected final void refreshBeanFactory() throws BeansException {
- if (hasBeanFactory()) {
- destroyBeans();
- closeBeanFactory();
- }
- try {
- DefaultListableBeanFactory beanFactory = createBeanFactory();
- beanFactory.setSerializationId(getId());
- customizeBeanFactory(beanFactory);
- loadBeanDefinitions(beanFactory);
- synchronized (this.beanFactoryMonitor) {
- this.beanFactory = beanFactory;
- }
- }
- catch (IOException ex) {
- throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
- }
- }
3. 加载bean定义,以读取xml的ApplicationContext为例
- 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);
- }
4. 调用beanFactoryProcessor的后置增强处理器
invokeBeanFactoryPostProcessors(beanFactory);
5. 注册beanPostProcessor
doGetBean - createBean -doCreateBean, doGetBean 时getSingleton放到三级缓存中
7.
- 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
- @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
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;
- }
- protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
- if (System.getSecurityManager() != null) {
- AccessController.doPrivileged(new PrivilegedAction
- @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;
- }
- @Override
- public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
- // Don't override the class with CGLIB if no overrides.
- if (bd.getMethodOverrides().isEmpty()) {
- Constructor> constructorToUse;
- synchronized (bd.constructorArgumentLock) {
- constructorToUse = (Constructor>) bd.resolvedConstructorOrFactoryMethod;
- if (constructorToUse == null) {
- final Class> clazz = bd.getBeanClass();
- if (clazz.isInterface()) {
- throw new BeanInstantiationException(clazz, "Specified class is an interface");
- }
- try {
- if (System.getSecurityManager() != null) {
- constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction
>() { - @Override
- public Constructor> run() throws Exception {
- return clazz.getDeclaredConstructor((Class[]) null);
- }
- });
- }
- else {
- constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
- }
- bd.resolvedConstructorOrFactoryMethod = constructorToUse;
- }
- catch (Exception ex) {
- throw new BeanInstantiationException(clazz, "No default constructor found", ex);
- }
- }
- }
- return BeanUtils.instantiateClass(constructorToUse);
- }
- else {
- // Must generate CGLIB subclass.
- return instantiateWithMethodInjection(bd, beanName, owner);
- }
- }
- public static
T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException { - Assert.notNull(ctor, "Constructor must not be null");
- try {
- ReflectionUtils.makeAccessible(ctor);
- return ctor.newInstance(args);
- }
- catch (InstantiationException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Is it an abstract class?", ex);
- }
- catch (IllegalAccessException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Is the constructor accessible?", ex);
- }
- catch (IllegalArgumentException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Illegal arguments for constructor", ex);
- }
- catch (InvocationTargetException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Constructor threw exception", ex.getTargetException());
- }
- protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
- if (System.getSecurityManager() != null) {
- AccessController.doPrivileged(new PrivilegedAction
- @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;
- }
5. 初始化广播器
注册监听器

- public static ConfigurableApplicationContext run(Class>[] primarySources, String[] args) {
- return new SpringApplication(primarySources).run(args);
- }
-
- public SpringApplication(Class>... primarySources) {
- this(null, primarySources);
- }
-
- /**
- * Create a new {@link SpringApplication} instance. The application context will load
- * beans from the specified primary sources (see {@link SpringApplication class-level}
- * documentation for details. The instance can be customized before calling
- * {@link #run(String...)}.
- * @param resourceLoader the resource loader to use
- * @param primarySources the primary bean sources
- * @see #run(Class, String[])
- * @see #setSources(Set)
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public SpringApplication(ResourceLoader resourceLoader, Class>... primarySources) {
- this.resourceLoader = resourceLoader;
- Assert.notNull(primarySources, "PrimarySources must not be null");
- this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
- this.webApplicationType = WebApplicationType.deduceFromClasspath();
- setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
- setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
- this.mainApplicationClass = deduceMainApplicationClass();
- }
注:此时初始化了一些监听器和初始化器, primarySources为启动的主类
- public ConfigurableApplicationContext run(String... args) {
- StopWatch stopWatch = new StopWatch();
- // 计时器开始
- stopWatch.start();
- ConfigurableApplicationContext context = null;
- Collection
exceptionReporters = new ArrayList<>(); - configureHeadlessProperty();
- // 通过SPI方式获取到实现了SpringApplicationRunListener监听器的staging()方法
- SpringApplicationRunListeners listeners = getRunListeners(args);
- listeners.starting();
- try {
- ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
- ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
- configureIgnoreBeanInfo(environment);
- Banner printedBanner = printBanner(environment);
- context = createApplicationContext();
- exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
- new Class[] { ConfigurableApplicationContext.class }, context);
- prepareContext(context, environment, listeners, applicationArguments, printedBanner);
- refreshContext(context);
- afterRefresh(context, applicationArguments);
- // 计时器结束
- stopWatch.stop();
- if (this.logStartupInfo) {
- new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
- }
- listeners.started(context);
- callRunners(context, applicationArguments);
- }
- catch (Throwable ex) {
- handleRunFailure(context, ex, exceptionReporters, listeners);
- throw new IllegalStateException(ex);
- }
-
- try {
- listeners.running(context);
- }
- catch (Throwable ex) {
- handleRunFailure(context, ex, exceptionReporters, null);
- throw new IllegalStateException(ex);
- }
- return context;
- }
- protected ConfigurableApplicationContext createApplicationContext() {
- Class> contextClass = this.applicationContextClass;
- if (contextClass == null) {
- try {
- switch (this.webApplicationType) {
- case SERVLET:
- contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
- break;
- case REACTIVE:
- contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
- break;
- default:
- contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
- }
- }
- catch (ClassNotFoundException ex) {
- throw new IllegalStateException(
- "Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
- }
- }
- return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
- }
注:其中创建的是org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext

注:其中AbstracApplicationContext中refresh定义了Spring实例化类的标准流程
- public void refresh() throws BeansException, IllegalStateException {
- synchronized (this.startupShutdownMonitor) {
- // Prepare this context for refreshing.
- 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();
- }
- }
- }
注:经过子类实现后,beanFactory为DefaultListableBeanFactory
- public AnnotationConfigServletWebServerApplicationContext() {
- this.reader = new AnnotatedBeanDefinitionReader(this);
- this.scanner = new ClassPathBeanDefinitionScanner(this);
- }
注:其中反射形式创建AnnotationConfigServletWebServerApplicationContext时,创建了两个对象,其中reader主要的作用理解是,向DefaultListableBeanFactory注册了内部使用的postProcessor,其中ConfigurationClassPostProcessor尤为重要。

- private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
- SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
- context.setEnvironment(environment);
- postProcessApplicationContext(context);
- applyInitializers(context);
- listeners.contextPrepared(context);
- if (this.logStartupInfo) {
- logStartupInfo(context.getParent() == null);
- logStartupProfileInfo(context);
- }
- // Add boot specific singleton beans
- ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
- beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
- if (printedBanner != null) {
- beanFactory.registerSingleton("springBootBanner", printedBanner);
- }
- if (beanFactory instanceof DefaultListableBeanFactory) {
- ((DefaultListableBeanFactory) beanFactory)
- .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
- }
- if (this.lazyInitialization) {
- context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
- }
- // Load the sources
- Set
- Assert.notEmpty(sources, "Sources must not be empty");
- load(context, sources.toArray(new Object[0]));
- listeners.contextLoaded(context);
- }
注:将启动类定义注入的DefaultListableBeanFactory
- protected void refresh(ApplicationContext applicationContext) {
- Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
- ((AbstractApplicationContext) applicationContext).refresh();
- }
注:也就是执行refresh标准化的13个函数
注:prepareRefresh()负责一些属性初始化工作,【TODO】, prepareBeanFactory()负责DefaultListableBeanFactory的一些属性赋值。
- protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
- // Tell the internal bean factory to use the context's class loader etc.
- beanFactory.setBeanClassLoader(getClassLoader());
- beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
- beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
-
- // Configure the bean factory with context callbacks.
- // 注意:这个主要是为了处理类实现的Aware接口是,bean初始化的一部分。
- beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
- beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
- beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
- beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
- beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
- beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
- beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
-
- // BeanFactory interface not registered as resolvable type in a plain factory.
- // MessageSource registered (and found for autowiring) as a bean.
- beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
- beanFactory.registerResolvableDependency(ResourceLoader.class, this);
- beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
- beanFactory.registerResolvableDependency(ApplicationContext.class, this);
-
- // Register early post-processor for detecting inner beans as ApplicationListeners.
- beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
-
- // Detect a LoadTimeWeaver and prepare for weaving, if found.
- if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
- beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
- // Set a temporary ClassLoader for type matching.
- beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
- }
-
- // Register default environment beans.
- if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
- beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
- }
- if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
- beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
- }
- if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
- beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
- }
- }
invokeBeanFactoryPostProcessors()方法,在这个方法中完成了bean定义的加载,并完成了Springboot的自动配置。在代码中线先调用postProcessBeanDefinitionRegistry方法,在调用postProcessBeanFactory方法。
- public static void invokeBeanFactoryPostProcessors(
- ConfigurableListableBeanFactory beanFactory, List
beanFactoryPostProcessors) { -
- // Invoke BeanDefinitionRegistryPostProcessors first, if any.
- Set
processedBeans = new HashSet<>(); -
- if (beanFactory instanceof BeanDefinitionRegistry) {
- BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
- List
regularPostProcessors = new ArrayList<>(); - List
registryProcessors = new ArrayList<>(); -
- for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
- if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
- BeanDefinitionRegistryPostProcessor registryProcessor =
- (BeanDefinitionRegistryPostProcessor) postProcessor;
- registryProcessor.postProcessBeanDefinitionRegistry(registry);
- registryProcessors.add(registryProcessor);
- }
- else {
- regularPostProcessors.add(postProcessor);
- }
- }
-
- // Do not initialize FactoryBeans here: We need to leave all regular beans
- // uninitialized to let the bean factory post-processors apply to them!
- // Separate between BeanDefinitionRegistryPostProcessors that implement
- // PriorityOrdered, Ordered, and the rest.
- List
currentRegistryProcessors = new ArrayList<>(); -
- // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- // 获取到ConfigurationClassPostProcessor的实例
- for (String ppName : postProcessorNames) {
- if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- // 调用ConfigurationClassPostProcessor的方法
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
- currentRegistryProcessors.clear();
-
- // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
- currentRegistryProcessors.clear();
-
- // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
- boolean reiterate = true;
- while (reiterate) {
- reiterate = false;
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (!processedBeans.contains(ppName)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- reiterate = true;
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
- currentRegistryProcessors.clear();
- }
-
- // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
- invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
- }
-
- else {
- // Invoke factory processors registered with the context instance.
- invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
- }
-
- // Do not initialize FactoryBeans here: We need to leave all regular beans
- // uninitialized to let the bean factory post-processors apply to them!
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
-
- // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
- // Ordered, and the rest.
- List
priorityOrderedPostProcessors = new ArrayList<>(); - List
orderedPostProcessorNames = new ArrayList<>(); - List
nonOrderedPostProcessorNames = new ArrayList<>(); - for (String ppName : postProcessorNames) {
- if (processedBeans.contains(ppName)) {
- // skip - already processed in first phase above
- }
- else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
- }
- else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
- orderedPostProcessorNames.add(ppName);
- }
- else {
- nonOrderedPostProcessorNames.add(ppName);
- }
- }
-
- // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
- sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
-
- // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
- List
orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); - for (String postProcessorName : orderedPostProcessorNames) {
- orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- sortPostProcessors(orderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
-
- // Finally, invoke all other BeanFactoryPostProcessors.
- List
nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); - for (String postProcessorName : nonOrderedPostProcessorNames) {
- nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
-
- // Clear cached merged bean definitions since the post-processors might have
- // modified the original metadata, e.g. replacing placeholders in values...
- beanFactory.clearMetadataCache();
- }
- private static void invokeBeanDefinitionRegistryPostProcessors(
- Collection extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
-
- for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
- postProcessor.postProcessBeanDefinitionRegistry(registry);
- }
- }
-
- /**
- * Invoke the given BeanFactoryPostProcessor beans.
- */
- private static void invokeBeanFactoryPostProcessors(
- Collection extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
-
- for (BeanFactoryPostProcessor postProcessor : postProcessors) {
- postProcessor.postProcessBeanFactory(beanFactory);
- }
- }
其中ConfigurationClassPostProcessor,帮助完成了bean定义的加载和自动配置需要的bean定义的加载。
- public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
- List
configCandidates = new ArrayList<>(); - String[] candidateNames = registry.getBeanDefinitionNames();
-
- for (String beanName : candidateNames) {
- BeanDefinition beanDef = registry.getBeanDefinition(beanName);
- if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
- if (logger.isDebugEnabled()) {
- logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
- }
- }
- else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
- configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
- }
- }
-
- // Return immediately if no @Configuration classes were found
- if (configCandidates.isEmpty()) {
- return;
- }
-
- // Sort by previously determined @Order value, if applicable
- configCandidates.sort((bd1, bd2) -> {
- int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
- int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
- return Integer.compare(i1, i2);
- });
-
- // Detect any custom bean name generation strategy supplied through the enclosing application context
- SingletonBeanRegistry sbr = null;
- if (registry instanceof SingletonBeanRegistry) {
- sbr = (SingletonBeanRegistry) registry;
- if (!this.localBeanNameGeneratorSet) {
- BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
- AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
- if (generator != null) {
- this.componentScanBeanNameGenerator = generator;
- this.importBeanNameGenerator = generator;
- }
- }
- }
-
- if (this.environment == null) {
- this.environment = new StandardEnvironment();
- }
-
- // Parse each @Configuration class
- ConfigurationClassParser parser = new ConfigurationClassParser(
- this.metadataReaderFactory, this.problemReporter, this.environment,
- this.resourceLoader, this.componentScanBeanNameGenerator, registry);
-
- Set
candidates = new LinkedHashSet<>(configCandidates); - Set
alreadyParsed = new HashSet<>(configCandidates.size()); - do {
- // candidates初始化,一般是启动类
- parser.parse(candidates);
- parser.validate();
-
- Set
configClasses = new LinkedHashSet<>(parser.getConfigurationClasses()); - configClasses.removeAll(alreadyParsed);
-
- // Read the model and create bean definitions based on its content
- if (this.reader == null) {
- this.reader = new ConfigurationClassBeanDefinitionReader(
- registry, this.sourceExtractor, this.resourceLoader, this.environment,
- this.importBeanNameGenerator, parser.getImportRegistry());
- }
- this.reader.loadBeanDefinitions(configClasses);
- alreadyParsed.addAll(configClasses);
-
- candidates.clear();
- if (registry.getBeanDefinitionCount() > candidateNames.length) {
- String[] newCandidateNames = registry.getBeanDefinitionNames();
- Set
oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames)); - Set
alreadyParsedClasses = new HashSet<>(); - for (ConfigurationClass configurationClass : alreadyParsed) {
- alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
- }
- for (String candidateName : newCandidateNames) {
- if (!oldCandidateNames.contains(candidateName)) {
- BeanDefinition bd = registry.getBeanDefinition(candidateName);
- if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
- !alreadyParsedClasses.contains(bd.getBeanClassName())) {
- candidates.add(new BeanDefinitionHolder(bd, candidateName));
- }
- }
- }
- candidateNames = newCandidateNames;
- }
- }
- while (!candidates.isEmpty());
-
- // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
- if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
- sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
- }
-
- if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
- // Clear cache in externally provided MetadataReaderFactory; this is a no-op
- // for a shared cache since it'll be cleared by the ApplicationContext.
- ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
- }
- }
parser.parse(andidates)
- public void parse(Set
configCandidates) { - for (BeanDefinitionHolder holder : configCandidates) {
- BeanDefinition bd = holder.getBeanDefinition();
- try {
- if (bd instanceof AnnotatedBeanDefinition) {
- parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
- }
- else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
- parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
- }
- else {
- parse(bd.getBeanClassName(), holder.getBeanName());
- }
- }
- catch (BeanDefinitionStoreException ex) {
- throw ex;
- }
- catch (Throwable ex) {
- throw new BeanDefinitionStoreException(
- "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
- }
- }
-
- this.deferredImportSelectorHandler.process();
- }
- protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
- processConfigurationClass(new ConfigurationClass(metadata, beanName));
- }
- protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
- if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
- return;
- }
-
- ConfigurationClass existingClass = this.configurationClasses.get(configClass);
- if (existingClass != null) {
- if (configClass.isImported()) {
- if (existingClass.isImported()) {
- existingClass.mergeImportedBy(configClass);
- }
- // Otherwise ignore new imported config class; existing non-imported class overrides it.
- return;
- }
- else {
- // Explicit bean definition found, probably replacing an import.
- // Let's remove the old one and go with the new one.
- this.configurationClasses.remove(configClass);
- this.knownSuperclasses.values().removeIf(configClass::equals);
- }
- }
-
- // Recursively process the configuration class and its superclass hierarchy.
- SourceClass sourceClass = asSourceClass(configClass);
- do {
- sourceClass = doProcessConfigurationClass(configClass, sourceClass);
- }
- while (sourceClass != null);
-
- this.configurationClasses.put(configClass, configClass);
- }
- @Nullable
- protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
- throws IOException {
-
- if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
- // Recursively process any member (nested) classes first
- // 处理内部类
- processMemberClasses(configClass, sourceClass);
- }
-
- // Process any @PropertySource annotations
- for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
- sourceClass.getMetadata(), PropertySources.class,
- org.springframework.context.annotation.PropertySource.class)) {
- if (this.environment instanceof ConfigurableEnvironment) {
- processPropertySource(propertySource);
- }
- else {
- logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
- "]. Reason: Environment must implement ConfigurableEnvironment");
- }
- }
-
- // Process any @ComponentScan annotations
- // 由于启动类带着ComponentScan注解,所以能扫描到启动类所在包下开始扫描
- Set
componentScans = AnnotationConfigUtils.attributesForRepeatable( - sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
- if (!componentScans.isEmpty() &&
- !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
- for (AnnotationAttributes componentScan : componentScans) {
- // The config class is annotated with @ComponentScan -> perform the scan immediately
- Set
scannedBeanDefinitions = - this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
- // Check the set of scanned definitions for any further config classes and parse recursively if needed
- for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
- BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
- if (bdCand == null) {
- bdCand = holder.getBeanDefinition();
- }
- if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
- parse(bdCand.getBeanClassName(), holder.getBeanName());
- }
- }
- }
- }
-
- // Process any @Import annotations
- processImports(configClass, sourceClass, getImports(sourceClass), true);
-
- // Process any @ImportResource annotations
- AnnotationAttributes importResource =
- AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
- if (importResource != null) {
- String[] resources = importResource.getStringArray("locations");
- Class extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
- for (String resource : resources) {
- String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
- configClass.addImportedResource(resolvedResource, readerClass);
- }
- }
-
- // Process individual @Bean methods
- Set
beanMethods = retrieveBeanMethodMetadata(sourceClass); - for (MethodMetadata methodMetadata : beanMethods) {
- configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
- }
-
- // Process default methods on interfaces
- processInterfaces(configClass, sourceClass);
-
- // Process superclass, if any
- if (sourceClass.getMetadata().hasSuperClass()) {
- String superclass = sourceClass.getMetadata().getSuperClassName();
- if (superclass != null && !superclass.startsWith("java") &&
- !this.knownSuperclasses.containsKey(superclass)) {
- this.knownSuperclasses.put(superclass, configClass);
- // Superclass found, return its annotation metadata and recurse
- return sourceClass.getSuperClass();
- }
- }
-
- // No superclass -> processing is complete
- return null;
- }
- public Set
parse(AnnotationAttributes componentScan, final String declaringClass) { - ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
- componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
-
- Class extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
- boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
- scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
- BeanUtils.instantiateClass(generatorClass));
-
- ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
- if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
- scanner.setScopedProxyMode(scopedProxyMode);
- }
- else {
- Class extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
- scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
- }
-
- scanner.setResourcePattern(componentScan.getString("resourcePattern"));
-
- for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
- for (TypeFilter typeFilter : typeFiltersFor(filter)) {
- scanner.addIncludeFilter(typeFilter);
- }
- }
- for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
- for (TypeFilter typeFilter : typeFiltersFor(filter)) {
- scanner.addExcludeFilter(typeFilter);
- }
- }
-
- boolean lazyInit = componentScan.getBoolean("lazyInit");
- if (lazyInit) {
- scanner.getBeanDefinitionDefaults().setLazyInit(true);
- }
-
- Set
basePackages = new LinkedHashSet<>(); - String[] basePackagesArray = componentScan.getStringArray("basePackages");
- for (String pkg : basePackagesArray) {
- String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
- ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
- Collections.addAll(basePackages, tokenized);
- }
- for (Class> clazz : componentScan.getClassArray("basePackageClasses")) {
- basePackages.add(ClassUtils.getPackageName(clazz));
- }
- if (basePackages.isEmpty()) {
- basePackages.add(ClassUtils.getPackageName(declaringClass));
- }
-
- scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
- @Override
- protected boolean matchClassName(String className) {
- return declaringClass.equals(className);
- }
- });
- return scanner.doScan(StringUtils.toStringArray(basePackages));
- }
- protected Set
doScan(String... basePackages) { - Assert.notEmpty(basePackages, "At least one base package must be specified");
- Set
beanDefinitions = new LinkedHashSet<>(); - for (String basePackage : basePackages) {
- Set
candidates = findCandidateComponents(basePackage); - for (BeanDefinition candidate : candidates) {
- ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
- candidate.setScope(scopeMetadata.getScopeName());
- String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
- if (candidate instanceof AbstractBeanDefinition) {
- postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
- }
- if (candidate instanceof AnnotatedBeanDefinition) {
- AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
- }
- if (checkCandidate(beanName, candidate)) {
- BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
- definitionHolder =
- AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
- beanDefinitions.add(definitionHolder);
- registerBeanDefinition(definitionHolder, this.registry);
- }
- }
- }
- return beanDefinitions;
- }
- public Set
findCandidateComponents(String basePackage) { - if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
- return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
- }
- else {
- return scanCandidateComponents(basePackage);
- }
- }
- private Set
scanCandidateComponents(String basePackage) { - Set
candidates = new LinkedHashSet<>(); - try {
- String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
- resolveBasePackage(basePackage) + '/' + this.resourcePattern;
- Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
- boolean traceEnabled = logger.isTraceEnabled();
- boolean debugEnabled = logger.isDebugEnabled();
- for (Resource resource : resources) {
- if (traceEnabled) {
- logger.trace("Scanning " + resource);
- }
- if (resource.isReadable()) {
- try {
- MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
- if (isCandidateComponent(metadataReader)) {
- ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
- sbd.setResource(resource);
- sbd.setSource(resource);
- if (isCandidateComponent(sbd)) {
- if (debugEnabled) {
- logger.debug("Identified candidate component class: " + resource);
- }
- candidates.add(sbd);
- }
- else {
- if (debugEnabled) {
- logger.debug("Ignored because not a concrete top-level class: " + resource);
- }
- }
- }
- else {
- if (traceEnabled) {
- logger.trace("Ignored because not matching any filter: " + resource);
- }
- }
- }
- catch (Throwable ex) {
- throw new BeanDefinitionStoreException(
- "Failed to read candidate component class: " + resource, ex);
- }
- }
- else {
- if (traceEnabled) {
- logger.trace("Ignored because not readable: " + resource);
- }
- }
- }
- }
- catch (IOException ex) {
- throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
- }
- return candidates;
- }
注:可以理解parse->processConfigurationClass(最后一句this.configurationClasses.put(configClass, configClass); 将处理的类入口参数类,进行存储)->doProcessConfigurationClass(识别扫描注解), 处理ComponentScan, 扫描出来的类【configuration,继续parse()】扫描过程中类注册到DefaultListableBeanFactory,和【processImports(此时只是存储import,自动配置的扫描类), import的类中没有实现部分接口,继续处理processConfigurationClass()】, 打头的parse启动后进行。
注:此时开始自动装载
this.deferredImportSelectorHandler.process();
- public void process() {
- List
deferredImports = this.deferredImportSelectors; - this.deferredImportSelectors = null;
- try {
- if (deferredImports != null) {
- DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
- deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
- deferredImports.forEach(handler::register);
- handler.processGroupImports();
- }
- }
- finally {
- this.deferredImportSelectors = new ArrayList<>();
- }
- }
- public void processGroupImports() {
- for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
- grouping.getImports().forEach(entry -> {
- ConfigurationClass configurationClass = this.configurationClasses.get(
- entry.getMetadata());
- try {
- // 注意,这里再次开始import,
- processImports(configurationClass, asSourceClass(configurationClass),
- asSourceClasses(entry.getImportClassName()), false);
- }
- catch (BeanDefinitionStoreException ex) {
- throw ex;
- }
- catch (Throwable ex) {
- throw new BeanDefinitionStoreException(
- "Failed to process import candidates for configuration class [" +
- configurationClass.getMetadata().getClassName() + "]", ex);
- }
- });
- }
- }
此时基本的类定义都扫描到了。其中重要的是AutoConfigurationImportSelector,负责的是自动化的配置加载springboot会把所有jar包下META-INF/spring.factories 中的key是org.springframework.boot.autoconfigure.EnableAutoConfiguration 所对应的值的bean放入容器中
- protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
- // 判断是否开启自动配置
- if (!isEnabled(annotationMetadata)) {
- return EMPTY_ENTRY;
- }
- // 获取@EnableAutoConfiguration注解的属性
- AnnotationAttributes attributes = getAttributes(annotationMetadata);
- // 从spring.factories文件中获取配置类的全限定名数组
- List
configurations = getCandidateConfigurations(annotationMetadata, attributes); - // 去重
- configurations = removeDuplicates(configurations);
- // 获取注解中exclude或excludeName排除的类集合
- Set
exclusions = getExclusions(annotationMetadata, attributes); - // 检查被排除类是否可以实例化,是否被自动配置所使用,否则抛出异常
- checkExcludedClasses(configurations, exclusions);
- // 去除被排除的类
- configurations.removeAll(exclusions);
- // 使用spring.factories配置文件中配置的过滤器对自动配置类进行过滤
- configurations = getConfigurationClassFilter().filter(configurations);
- // 抛出事件
- fireAutoConfigurationImportEvents(configurations, exclusions);
- return new AutoConfigurationEntry(configurations, exclusions);
- }
过滤:
- private ConfigurationClassFilter getConfigurationClassFilter() {
- if (this.configurationClassFilter == null) {
- // 获取AutoConfigurationImportFilter过滤器列表
- List
filters = getAutoConfigurationImportFilters(); - for (AutoConfigurationImportFilter filter : filters) {
- invokeAwareMethods(filter);
- }
- this.configurationClassFilter = new ConfigurationClassFilter(this.beanClassLoader, filters);
- }
- return this.configurationClassFilter;
- }
开始创建对象
- protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
- // Initialize conversion service for this context.
- 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));
- }
-
- // Register a default embedded value resolver if no bean post-processor
- // (such as a PropertyPlaceholderConfigurer bean) registered any before:
- // at this point, primarily for resolution in annotation attribute values.
- if (!beanFactory.hasEmbeddedValueResolver()) {
- beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
- }
-
- // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
- 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);
-
- // Allow for caching all bean definition metadata, not expecting further changes.
- beanFactory.freezeConfiguration();
-
- // Instantiate all remaining (non-lazy-init) singletons.
- beanFactory.preInstantiateSingletons();
- }
创建对象主要知识点是3级缓存和对象的生命周期问题
getBean->doGetBean->getSingleton(lamdba表达式)->createBean->doCreateBean
- protected Object getSingleton(String beanName, boolean allowEarlyReference) {
- Object singletonObject = this.singletonObjects.get(beanName);
- if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
- synchronized (this.singletonObjects) {
- singletonObject = this.earlySingletonObjects.get(beanName);
- if (singletonObject == null && allowEarlyReference) {
- ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
- if (singletonFactory != null) {
- singletonObject = singletonFactory.getObject();
- this.earlySingletonObjects.put(beanName, singletonObject);
- this.singletonFactories.remove(beanName);
- }
- }
- }
- }
- return singletonObject;
- }
- public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
- Assert.notNull(beanName, "Bean name 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);
- }
- if (newSingleton) {
- addSingleton(beanName, singletonObject);
- }
- }
- return singletonObject;
- }
- }
- protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
- throws BeanCreationException {
-
- // 实例化类,并形成包装wrapp类,方便属性的注入.
- BeanWrapper instanceWrapper = null;
- if (mbd.isSingleton()) {
- instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
- }
- if (instanceWrapper == null) {
- instanceWrapper = createBeanInstance(beanName, mbd, args);
- }
- final Object bean = instanceWrapper.getWrappedInstance();
- Class> beanType = instanceWrapper.getWrappedClass();
- if (beanType != NullBean.class) {
- mbd.resolvedTargetType = beanType;
- }
-
- // Allow post-processors to modify the merged bean definition.
- 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;
- }
- }
-
- // 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.isTraceEnabled()) {
- logger.trace("Eagerly caching bean '" + beanName +
- "' to allow for resolving potential circular references");
- }
- addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
- }
-
- // Initialize the bean instance.
- Object exposedObject = bean;
- try {
- populateBean(beanName, mbd, instanceWrapper);
- 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;
- }
属性注入:
通过bean的定义属性值,解决属性的注入。
- protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
- if (bw == null) {
- if (mbd.hasPropertyValues()) {
- 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.
- if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
- for (BeanPostProcessor bp : getBeanPostProcessors()) {
- if (bp instanceof InstantiationAwareBeanPostProcessor) {
- InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
- if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
- return;
- }
- }
- }
- }
-
- PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
-
- int resolvedAutowireMode = mbd.getResolvedAutowireMode();
- if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
- MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
- // Add property values based on autowire by name if applicable.
- if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
- autowireByName(beanName, mbd, bw, newPvs);
- }
- // Add property values based on autowire by type if applicable.
- if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
- autowireByType(beanName, mbd, bw, newPvs);
- }
- pvs = newPvs;
- }
-
- boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
- boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
-
- PropertyDescriptor[] filteredPds = null;
- if (hasInstAwareBpps) {
- if (pvs == null) {
- pvs = mbd.getPropertyValues();
- }
- for (BeanPostProcessor bp : getBeanPostProcessors()) {
- if (bp instanceof InstantiationAwareBeanPostProcessor) {
- InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
- PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
- if (pvsToUse == null) {
- if (filteredPds == null) {
- filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
- }
- pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
- if (pvsToUse == null) {
- return;
- }
- }
- pvs = pvsToUse;
- }
- }
- }
- if (needsDepCheck) {
- if (filteredPds == null) {
- filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
- }
- checkDependencies(beanName, mbd, filteredPds, pvs);
- }
-
- if (pvs != null) {
- applyPropertyValues(beanName, mbd, bw, pvs);
- }
- }

doCreateBean
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
AOP代理
- protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
- Object exposedObject = bean;
- if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
- for (BeanPostProcessor bp : getBeanPostProcessors()) {
- if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
- SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
- exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
- }
- }
- }
- return exposedObject;
- }
- public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
- if (bean != null) {
- Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
- if (this.earlyProxyReferences.remove(cacheKey) != bean) {
- return this.wrapIfNecessary(bean, beanName, cacheKey);
- }
- }
-
- return bean;
- }
为什么用三级缓存解决循环依赖,二级缓存不行,因为如果testService1被代理过,假设用二级缓存,此时testService2中注入的testService1是半成品的对象。此时testService1的创建流程继续往下走时,走到AbstractAutoProxyCreator会再次创建代理对象,此时testService2中对应的testService1为对象,而spring容器中testService1的BeanName对应的为代理对象。导致一个beanName对应了两个对象。由于testService1位单例。所以用三级缓存解决,testService1中解决这个问题。利用了earlyProxyReferences来解决这个问题。
bean的生命周期
- BeanNameAware's setBeanName
- BeanClassLoaderAware's setBeanClassLoader
- BeanFactoryAware's setBeanFactory
- EnvironmentAware's setEnvironment
- EmbeddedValueResolverAware's setEmbeddedValueResolver
- ResourceLoaderAware's setResourceLoader (only applicable when running in an application context)
- ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context)
- MessageSourceAware's setMessageSource (only applicable when running in an application context)
- ApplicationContextAware's setApplicationContext (only applicable when running in an application context)
- ServletContextAware's setServletContext (only applicable when running in a web application context)
- postProcessBeforeInitialization methods of BeanPostProcessors
- InitializingBean's afterPropertiesSet
- a custom init-method definition
- postProcessAfterInitialization methods of BeanPostProcessors
1.
- private void invokeAwareMethods(final String beanName, final Object bean) {
- if (bean instanceof Aware) {
- if (bean instanceof BeanNameAware) {
- ((BeanNameAware) bean).setBeanName(beanName);
- }
- if (bean instanceof BeanClassLoaderAware) {
- ClassLoader bcl = getBeanClassLoader();
- if (bcl != null) {
- ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
- }
- }
- if (bean instanceof BeanFactoryAware) {
- ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
- }
- }
- }
2. refresh->prepareBeanFactory->ApplicationContextAwareProcessor()
在准备prepareBeanFactory时,添加ApplicationContextAwareProcessor
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
- bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
- bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
- return bean;
- }
-
- AccessControlContext acc = null;
-
- if (System.getSecurityManager() != null) {
- acc = this.applicationContext.getBeanFactory().getAccessControlContext();
- }
-
- if (acc != null) {
- AccessController.doPrivileged((PrivilegedAction
- invokeAwareInterfaces(bean);
- return null;
- }, acc);
- }
- else {
- invokeAwareInterfaces(bean);
- }
-
- return bean;
- }
- private void invokeAwareInterfaces(Object bean) {
- if (bean instanceof EnvironmentAware) {
- ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
- }
- if (bean instanceof EmbeddedValueResolverAware) {
- ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
- }
- if (bean instanceof ResourceLoaderAware) {
- ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
- }
- if (bean instanceof ApplicationEventPublisherAware) {
- ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
- }
- if (bean instanceof MessageSourceAware) {
- ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
- }
- if (bean instanceof ApplicationContextAware) {
- ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
- }
- }
3. refresh->postProcessBeanFactory
- protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
- beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
- beanFactory.ignoreDependencyInterface(ServletContextAware.class);
- registerWebApplicationScopes();
- }
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- if (getServletContext() != null && bean instanceof ServletContextAware) {
- ((ServletContextAware) bean).setServletContext(getServletContext());
- }
- if (getServletConfig() != null && bean instanceof ServletConfigAware) {
- ((ServletConfigAware) bean).setServletConfig(getServletConfig());
- }
- return bean;
- }

InitDestroyAnnotationBeanPostProcessor
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
- try {
- metadata.invokeInitMethods(bean, beanName);
- }
- catch (InvocationTargetException ex) {
- throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
- }
- catch (Throwable ex) {
- throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
- }
- return bean;
- }
4. @PostConstruct方法
5. InitializingBean->afterPropertiesSet方法
6.@init-method
- protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
- throws Throwable {
-
- boolean isInitializingBean = (bean instanceof InitializingBean);
- if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
- if (logger.isTraceEnabled()) {
- logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
- }
- if (System.getSecurityManager() != null) {
- try {
- AccessController.doPrivileged((PrivilegedExceptionAction
- ((InitializingBean) bean).afterPropertiesSet();
- return null;
- }, getAccessControlContext());
- }
- catch (PrivilegedActionException pae) {
- throw pae.getException();
- }
- }
- else {
- ((InitializingBean) bean).afterPropertiesSet();
- }
- }
-
- if (mbd != null && bean.getClass() != NullBean.class) {
- String initMethodName = mbd.getInitMethodName();
- if (StringUtils.hasLength(initMethodName) &&
- !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
- !mbd.isExternallyManagedInitMethod(initMethodName)) {
- invokeCustomInitMethod(beanName, bean, mbd);
- }
- }
- }
postProcessAfterInitialization
- public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
- throws BeansException {
-
- Object result = existingBean;
- for (BeanPostProcessor processor : getBeanPostProcessors()) {
- Object current = processor.postProcessAfterInitialization(result, beanName);
- if (current == null) {
- return result;
- }
- result = current;
- }
- return result;
- }