現在開始進入正題,開啓我們對Spring源碼的分析。那麼首先看下面的代碼:
public static void main(String[] args){
//創建Spring容器,那麼spring容器都經歷了撒?怎麼完成創建的呢?又是如何實現組件的掃描呢?
AnnotationConfigApplicationContext applicationContext
= new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println(applicationContext.getBean("a"));
}
@ComponentScan
@Configuration
public class MyConfig {
@Bean
String userService(){
return "userService";
}
@Bean
MessageService messageService(){
return new MessageServiceImpl();
}
@Bean
Integer count(){
return 3;
}
}
AnnotationConfigApplicationContext是實現註解驅動的ApplicationContext。實現了AnnotationConfigRegistry接口,可以通過包注入,可以通過Class註冊。
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();//調用無參構造器
register(annotatedClasses);
refresh();
}
public AnnotationConfigApplicationContext() {
//super();學習過java基礎的都知道,會先調用父類的構造函數,如果不寫,編譯器會默認給你補充上。
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//這裏就是 super()。父類GenericApplicationContext.class
public GenericApplicationContext() {
//創建了一個DefaultListableBeanFactory,這裏也調用了它的父類的構造函數
this.beanFactory = new DefaultListableBeanFactory();
}
//GenericApplicationContext.class 的父類AbstractApplicationContext
public AbstractApplicationContext() {
//這裏ResourceLoader 用來加載資源,生成Resource列表
this.resourcePatternResolver = getResourcePatternResolver();
}
//組合起來就是:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this.resourcePatternResolver = getResourcePatternResolver();
this.beanFactory = new DefaultListableBeanFactory();
//我們來看看這裏,構造函數做了什麼
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
register(annotatedClasses);
refresh();
}
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);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
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);
//註冊ConfigurationClassPostProcessor,此類用於處理@Configuration註解
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));
}
//註冊AutowiredAnnotationBeanPostProcessor,處理依賴注入@Autowired等等,反正依賴注入都是這個類
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));
}
//處理@EnvetListener註解,後續講spring事件詳細講
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;
}
//初始化註冊完了後就是register(annotatedClasses);這一步後調用reader 來註冊,將傳入的class解析成BeanDefinition並注入到容器中。
接下就繼續走refresh();
1、Spring容器refresh過程分析
refresh就是spring容器啓動的核心流程,前面的流程可以看做是初始化,refresh就是正在啓動流程。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 初始化一些啓動值
prepareRefresh();
//獲取ConfigurableListableBeanFactory ,前面準備工作在構造函數,這裏獲取也是一樣
//this.beanFactory = new DefaultListableBeanFactory();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//這裏添加了兩個BeanPostProcesser,處理Aware接口,一個是處理ApplicationListenerDetector
prepareBeanFactory(beanFactory);
try {
// 空的,如果子類需要對ConfigurableListableBeanFactory進行額外的配置,可以實現這個接口,比如檢測其他接口
postProcessBeanFactory(beanFactory);
/*
核心方法,調用BeanFactoryPostProcessor,之前註冊的@Configuration註解的處理器。這裏調用,
1、先調用BeanDefinitionRegistryPostProcessor,分優先級
2、調用BeanFactoryPostProcessor
*/
invokeBeanFactoryPostProcessors(beanFactory);
// 註冊BeanPostProcessor
registerBeanPostProcessors(beanFactory);
// 空的
initMessageSource();
// 初始化ApplicationEventMulticaster,如果沒有配置就用默認的,默認的沒有線程池
initApplicationEventMulticaster();
// 留給子類
onRefresh();
// 註冊監聽器ApplicationListener 或者使用註解 @EnventListener
registerListeners();
// 初始化所有 (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();
}
}
}