我們前一章介紹了spring的整體架構以及模塊劃分,也已經將代碼導入ide中,那么接下來就要開始讓人心動的Spring源碼之旅了。
1、默認的Spring啟動器
@SpringBootApplication
@ComponentScan(basePackages = {"com"})
public class SpringSourceApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringSourceApplication.class, args);
}
}
該方法是Springboot的啟動類
2、進入SpringApplication.java
public static ConfigurableApplicationContext run(Object source, String... args) {
return run(new Object[] { source }, args);
}
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return new SpringApplication(sources).run(args);
}
這里創建了一個SpringApplication方法,執行run方法,返回一個ConfigurableApplicationContext,這只是一個接口而已,根據名稱來看,這是一個可配置的應用程序上下文。
3、進入run方法
SpringApplication(sources)這個類的初始化就先不看,這里面調用了initialize()方法,主要完成了當前的運行環境,以及設置了ApplicationListener相關的東西,這里我們先不做分析,直接進入run方法。
public ConfigurableApplicationContext run(String... args) {
//記錄程序運行時間
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
/**
* 設置headless模式
* 在我們的例子中該屬性會被設置為true,因為我們開發的是服務器程序,
* 一般運行在沒有顯示器和鍵盤的環境。關于java中的headless模式
*/
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
bindToSpringApplication(environment);
Banner printedBanner = printBanner(environment);
/**
* 它創建出來的是ConfigurableApplicationContext類的實例對象
*AnnotationConfigEmbeddedWebApplicationContext
*/
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
/**
* 該方法對context進行了預設置,設置了ResourceLoader和ClassLoader,
* 并向bean工廠中添加了一個beanNameGenerator
*/
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
/**
* prepareContext()已經做好了refresh上下文的基礎準備工作
* spring對ApplicationContext進行了向下轉型,
* 轉型后的類型為:AbstractApplicationContex,并調用了它的refresh()方法
* 詳見方法內部實現
*/
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
try代碼塊中是我們最核心的功能,代碼中也添加了一部分的注釋。我們先看context的創建過程即進入到createApplicationContext()方法。
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
//此處采用反射獲取WebApplicationContext
contextClass = Class.forName(DEFAULT_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);
}
DEFAULT_WEB_CONTEXT_CLASS --->AnnotationConfigEmbeddedWebApplicationContext
接下來執行AnnotationConfigEmbeddedWebApplicationContext的構造方法
public AnnotationConfigEmbeddedWebApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
上面實例化了AnnotatedBeanDefinitionReader以及ClassPathBeanDefinitionScanner
實例化AnnotatedBeanDefinitionReader
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
接下來是調用
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
實例化 ConditionEvaluator,將其屬性ConditionContextImpl賦值
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
具體實現如下:
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
//獲取beanfactory信息,Spring IOC的核心
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry)
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(4);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
上面代碼比較長,我們來分開解析
- 1、DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
由wrap就可以看出此處使用的是裝飾器模式,registry包裹成一個指定的beanFactory
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
if (registry instanceof DefaultListableBeanFactory) {
return (DefaultListableBeanFactory) registry;
}
else if (registry instanceof GenericApplicationContext) {
//此處 GenericApplicationContext構造函數初始化beanFactory為DefaultListableBeanFactory
return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
}
else {
return null;
}
}
代碼執行到registry instanceof GenericApplicationContext(通過類繼承結構可得到),隨后調用GenericApplicationContext#getDefaultListableBeanFactory()方法,GenericApplicationContext在構造方法中實例化了屬性beanFactory的值為DefaultListableBeanFactory:
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
其構造優先于AnnotationConfigEmbeddedWebApplicationContext構造方法執行。
以上獲得了BeanFactory信息
代碼的構建請參考 github
該地址有相應代碼的注釋