Back to Javatutorial

Spring启动流程(四):启动前的准备工作

docs/Spring全家桶/Spring源码分析/Spring启动流程/Spring启动流程(四):启动前的准备工作.md

1.0.07.8 KB
Original Source

ɰɨ󣬽žͿʼ spring ˣ AbstractApplicationContext#refresh ÷һ 13 Ҳ spring ̣

ϵдӱĿʼ𲽷 13 ̽ spring ̡

1. ǰ׼prepareRefresh()

prepareRefresh() £

|-AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
 |-AbstractApplicationContext#refresh
  |-AbstractApplicationContext#prepareRefresh

£

protected void prepareRefresh() {
    // Switch to active.
    this.startupDate = System.currentTimeMillis();
    this.closed.set(false);
    this.active.set(true);

    // ʼļûоʵ֣һûչ
    initPropertySources();

    // 黷
    getEnvironment().validateRequiredProperties();

    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    } else {
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }

    this.earlyApplicationEvents = new LinkedHashSet<>();
}

δȽϼ򵥣ʱ䡢״̬ļ顢Եijʼȡ

2. ȡ beanFactory: obtainFreshBeanFactory()

ٸ obtainFreshBeanFactory() £

AbstractApplicationContext#obtainFreshBeanFactory

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    refreshBeanFactory();
    // ظոմ BeanFactory
    return getBeanFactory();
}

refresh BeanFactoryȻٷ BeanFactoryǼ refreshBeanFactory()

GenericApplicationContext#refreshBeanFactory

@Override
protected final void refreshBeanFactory() throws IllegalStateException {
    // ʡһЩжϴ
    this.beanFactory.setSerializationId(getId());
}

ؼֻһУ beanFactory SerializationId.

ٻعͷ getBeanFactory()

GenericApplicationContext#getBeanFactory

public final ConfigurableListableBeanFactory getBeanFactory() {
    return this.beanFactory;
}

͸ˣ˵ǰ beanFactory beanFactory ڷ AnnotationConfigApplicationContext 췽ʱģΪ DefaultListableBeanFactory.

3. ׼ beanFactory: prepareBeanFactory(beanFactory)

Ǽ prepareBeanFactory(beanFactory)

AbstractApplicationContext#prepareBeanFactory

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // ΪصǰApplicationContext
    beanFactory.setBeanClassLoader(getClassLoader());
    //  BeanExpressionResolverbeanʽ
    beanFactory.setBeanExpressionResolver(
            new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    // Ա༭֧
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // Springһչ
    // ʵAwareӿڵbeanڳʼʱ processorص
    // ǺܳãǻΪ˻ȡ ApplicationContext  implement ApplicationContextAware
    // ע⣺ص ApplicationContextAwareḺص EnvironmentAwareResourceLoaderAware 
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

    // 漸е˼ǣij bean ¼ӿڵʵ࣬
    // ԶװʱǣSpring ͨʽЩ
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    // 漸оΪļ bean ֵ bean ¼עӦֵ
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

     // һôApplicationListenerDetector˺ôʵBeanPostProcessorӿ
     beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // beanΪloadTimeWeaverbeanעһBeanPostProcessor
    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()));
    }

    // ûж "environment"  beanô Spring  "ֶ" עһ
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    // ûж "systemProperties"  beanô Spring  "ֶ" עһ
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, 
                getEnvironment().getSystemProperties());
    }
    // ûж "systemEnvironment"  beanô Spring  "ֶ" עһ
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, 
                getEnvironment().getSystemEnvironment());
    }
}

Ƕ beanFactory һЩ׼һЩԣһЩ bean ȣ붼ע⣬Ͳظ˵ˡ

beanFactory ApplicationListenerDetector Ҫ£شΪ beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));ǿ ApplicationListenerDetector

org.springframework.context.support.ApplicationContextAwareProcessor

class ApplicationContextAwareProcessor implements BeanPostProcessor {
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    // ʡһЩ
    AccessControlContext acc = null;
    if (System.getSecurityManager() != null) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }
    if (acc != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareInterfaces(bean);
            return null;
        }, acc);
    } else {
        invokeAwareInterfaces(bean);
    }
        return bean;
    }

    // ص Awareӿ
    private void invokeAwareInterfaces(Object bean) {
        //  EnvironmentAware#setEnvironment 
        if (bean instanceof EnvironmentAware) {
            ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
        }
        //  EmbeddedValueResolverAware#setEmbeddedValueResolver 
        if (bean instanceof EmbeddedValueResolverAware) {
            ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
        }
        //  ResourceLoaderAware#setResourceLoader 
        if (bean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
        }
        //  ApplicationEventPublisherAware#setApplicationEventPublisher 
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
        }
        //  MessageSourceAware#setMessageSource 
        if (bean instanceof MessageSourceAware) {
            ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
        }
        //  ApplicationContextAware#setApplicationContext 
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }

    // ʡ
}

Կ

  1. ʵ BeanPostProcessor ӿڣ
  2. postProcessBeforeInitialization BeanPostProcessor ṩΪؼĴ invokeAwareInterfaces(bean);
  3. invokeAwareInterfaces ֻһϵеķ

BeanPostProcessor ĵķԲο spring ֮ BeanPostProcessors ڸã

ˣĵķ͵ˣĽ spring ʱ beanFactory ׼ݽϼ򵥣һͼܽ±ݣ


ԭӣhttps://my.oschina.net/funcy/blog/4633169 ߸ˮƽд֮ӭָԭףҵתϵ߻Ȩҵתע