Spring代码阅读:(1)ClassPathXmlApplicationContext类说开去

类的设计

在这里插入图片描述
继承和实现了一系列接口
比如描述生命周期的

public interface Lifecycle {
    
    
    void start();

    void stop();

    boolean isRunning();
}

在AbstractApplicationContext中,写了核心的refresh的设计如下

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

postProcessBeanFactory

finishBeanFactoryInitialization

其中,在finishBeanFactoryInitialization完成用户定义的非懒加载的类的初始化

//org.springframework.beans.BeanUtils
			ReflectionUtils.makeAccessible(ctor);
			return ctor.newInstance(args);

然后调用

		try {
    
    
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
    
    
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}

populateBean完成依赖注入。

initializeBean进行初始化。
initializeBean代码如下

//org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:436

	protected Object createProxy(
			Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
    
    

		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
    
    
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}

		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.copyFrom(this);

		if (!proxyFactory.isProxyTargetClass()) {
    
    
			if (shouldProxyTargetClass(beanClass, beanName)) {
    
    
				proxyFactory.setProxyTargetClass(true);
			}
			else {
    
    
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}

		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		proxyFactory.addAdvisors(advisors);
		proxyFactory.setTargetSource(targetSource);
		customizeProxyFactory(proxyFactory);

		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
    
    
			proxyFactory.setPreFiltered(true);
		}

		return proxyFactory.getProxy(getProxyClassLoader());
	}

JdkDynamicAopProxy底层使用了sun.misc.ProxyGenerator#generateClassFile来生成代码文件。然后使用classLoader进行加载。这就是标准的java动态代理机制。
注意,此时,生成的类知识传入了类名和其实现的接口,并不包含具体的实现。最后调用

    private static native Object newInstance0(Constructor<?> var0, Object[] var1) throws InstantiationException, IllegalArgumentException, InvocationTargetException;

传入JdkDynamicAopProxy对象。
直接查看对象有点难,我们找一个网商已经搞好的。

/*
 * Decompiled with CFR 0_110.
 * 
 * Could not load the following classes:
 *  com.sun.proxy.$Proxy0
 *  ctgu.bytecode.proxy.service.HelloService
 */
package com.sun.proxy;

import ctgu.bytecode.proxy.service.HelloService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0
extends Proxy
implements HelloService {
    
    
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public $Proxy0(InvocationHandler invocationHandler) {
    
    
        super(invocationHandler);
    }

    public final boolean equals(Object object) {
    
    
        try {
    
    
            return (Boolean)this.h.invoke((Object)this, m1, new Object[]{
    
    object});
        }
        catch (Error | RuntimeException v0) {
    
    
            throw v0;
        }
        catch (Throwable var2_2) {
    
    
            throw new UndeclaredThrowableException(var2_2);
        }
    }

    public final String sayHello(String string) {
    
    
        try {
    
    
            return (String)this.h.invoke((Object)this, m3, new Object[]{
    
    string});
        }
        catch (Error | RuntimeException v0) {
    
    
            throw v0;
        }
        catch (Throwable var2_2) {
    
    
            throw new UndeclaredThrowableException(var2_2);
        }
    }

    public final String toString() {
    
    
        try {
    
    
            return (String)this.h.invoke((Object)this, m2, null);
        }
        catch (Error | RuntimeException v0) {
    
    
            throw v0;
        }
        catch (Throwable var1_1) {
    
    
            throw new UndeclaredThrowableException(var1_1);
        }
    }

    public final int hashCode() {
    
    
        try {
    
    
            return (Integer)this.h.invoke((Object)this, m0, null);
        }
        catch (Error | RuntimeException v0) {
    
    
            throw v0;
        }
        catch (Throwable var1_1) {
    
    
            throw new UndeclaredThrowableException(var1_1);
        }
    }

    static {
    
    
        try {
    
    
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("ctgu.bytecode.proxy.service.HelloService").getMethod("sayHello", Class.forName("java.lang.String"));
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            return;
        }
        catch (NoSuchMethodException var1) {
    
    
            throw new NoSuchMethodError(var1.getMessage());
        }
        catch (ClassNotFoundException var1_1) {
    
    
            throw new NoClassDefFoundError(var1_1.getMessage());
        }
    }
}

AbstractRefreshableApplicationContext持有一个DefaultListableBeanFactory对象。这个对象就是用于生成对象的。
在这里插入图片描述
DefaultListableBeanFactory同时维护所有bean的定义。


	/** Map of bean definition objects, keyed by bean name */
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256);

BeanDefinition就是在xml中我们配置的内容。

猜你喜欢

转载自blog.csdn.net/define_us/article/details/111053194
今日推荐