启动类
ClassPathXmlApplicationContext xml启动
AnnotationConfigApplicationContext class启动
以下是AnnotationConfigApplicationContext的启动解析
/*** 创建一个新的注解configapplicationcontext,派生bean定义*来自给定的带注释的类,并自动刷新上下文。* @param注释类一个或多个注释类,例如{@link Configuration @Configuration}类*/public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {this();register(annotatedClasses);refresh();}
其中的this()
/**
*创建一个新的需要填充的注释configapplicationcontext
*通过{@link #register}调用,然后手动{@linkplain #refresh refresh}。
*/
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
*如果可能,从给定的注册表获取环境,否则返回一个新的
* StandardEnvironment。
*/
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry instanceof EnvironmentCapable) {
return ((EnvironmentCapable) registry).getEnvironment();
}
return new StandardEnvironment();
}
/**
*为给定的bean工厂和创建一个新的{@code ClassPathBeanDefinitionScanner}
在评估bean定义配置文件元数据时使用给定的{@link环境}。
* @param注册表{@code BeanFactory}将bean定义加载到表单中
* of a {@code BeanDefinitionRegistry}
是否包括默认的过滤器
* {@link org.springframework.stereotype。组件@ Component},
* {@link org.springframework.stereotype。库@},
* {@link org.springframework.stereotype。服务@ Service},
* {@link org.springframework.stereotype。Controller @Controller}构造型注解
* @param environment在计算bean时使用的Spring {@link environment}
*定义配置文件元数据
要使用的{@link resourceLoader}
* @since 4.3.6
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, @Nullable ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(resourceLoader);
}
this.register() 注册
appConfig.class —-> AnnotatedGenericBeanBefinition
beanDefinitionMap
1.org.springframework.context.annotation.internalConfigurationAnnotationProcessor -> 内部配置注释处理器
2.org.springframework.context.event.internalEventListenerFactory -> 内部事件侦听器工厂
3.org.springframework.context.event.internalEventListenerProcessor -> 内部事件监听器处理器
4.org.springframework.context.annotation.internalAutowiredAnnotationProcessor -> 内部自动标注处理器
5.org.springframework.context.annotation.internalCommonAnnotationProcessor -> 内部公共注释处理机
6.org.springframework.context.annotation.internalRequiredAnnotationProcessor ->内部所需注释处理机
7.appConfig.class —-> AnnotatedGenericBeanBefinition 注入的配置参数
/**
*注册一个或多个要处理的带注释的类。
注意{@link #refresh()}必须为上下文调用
完全处理新类。
* @param注释类一个或多个注释类,
例如{@link Configuration @Configuration}类
* @see #扫描(String…)
* @see # refresh ()
*/
public void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
this.reader.register(annotatedClasses);
}
/**
注册来自给定bean类的一个bean,从它派生出元数据
* class-declared注释。
* @param注释了bean的类
* @param instanceSupplier创建bean实例的回调
*(可能是{@code null})
* @param为bean指定一个显式的名称
* @param修饰符特定的修饰符注释,如果有的话,
除了bean类级别的限定符之外
类的一个或多个回调
*工厂的{@link BeanDefinition},例如设置一个lazy-init或主标志
* @since 5.0
*/
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(instanceSupplier);
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
refresh()
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 为刷新准备此上下文。
prepareRefresh();
// 告诉子类刷新内部bean工厂。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备bean工厂,以便在此上下文中使用。
prepareBeanFactory(beanFactory);
try {
// 允许在上下文子类中对bean工厂进行后处理。
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// 调用上下文中注册为bean的工厂处理器。
registerBeanPostProcessors(beanFactory);
// 初始化此上下文的消息源。
initMessageSource();
// 为此上下文初始化事件多播程序。
initApplicationEventMulticaster();
// 初始化特定上下文子类中的其他特殊bean。
onRefresh();
// 检查侦听器bean并注册它们。
registerListeners();
// 实例化所有剩余的(非lazy-init)单例。
finishBeanFactoryInitialization(beanFactory);
// 最后一步:发布相应的事件。
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 重新释放资源
// 销毁已经创建的单例,以避免挂起资源。
destroyBeans();
// 重置“活跃”的旗帜。
cancelRefresh(ex);
// 将异常传播给调用者
throw ex;
}
finally {
//在Spring的内核中重置常用的内省缓存,因为我们
//可能不再需要单例bean的元数据了……
resetCommonCaches();
}
}
}
prepareRefresh()
/**
*准备此上下文用于刷新、设置其启动日期和
*活动标志,并执行任何初始化属性源。
*/
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// Initialize any placeholder property sources in the context environment.
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
prepareRefresh
/**
*准备此上下文用于刷新、设置其启动日期和
*活动标志,并执行任何初始化属性源
*/
protected void prepareRefresh() {
// //切换到active。
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// 在上下文环境中初始化任何占位符属性源。
initPropertySources();
//验证所有标记为需要的属性都是可解析的:
//看到ConfigurablePropertyResolver # setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
