现在开始进入正题,开启我们对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();
}
}
}