以AnnotationConfigApplicationContext來學(xué)習(xí)ioc容器的初始化過程
AnnotationConfigApplicationContext的構(gòu)造函數(shù)
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
this()函數(shù)調(diào)用默認(rèn)構(gòu)造函數(shù)
public AnnotationConfigApplicationContext() {
// 給容器添加注解型bean配置信息的閱讀器
this.reader = new AnnotatedBeanDefinitionReader(this);
// 添加類路徑下的bean配置類的掃描器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
- register()方法
public void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
//調(diào)用AnnotatedBeanDefinitionReader的register方法
this.reader.register(annotatedClasses);
}
- 進入到AnnotatedBeanDefinitionReader的register方法里面
public void register(Class<?>... annotatedClasses) {
for (Class<?> annotatedClass : annotatedClasses) {
// 該循環(huán)就是先將配置的config類信息優(yōu)先加載進去
registerBean(annotatedClass);
}
}
例如:
public static void main(String [] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class, SecondConfig.class);
Person person = (Person) context.getBean(Person.class);
Cat cat = (Cat) context.getBean(Cat.class);
log.info(person.toString());
log.info(cat.toString());
}
當(dāng)顯式創(chuàng)建一個容器,傳遞容器的配置類則會優(yōu)先將MainConfig.class和SecondConfig.class這兩個類的BeanDefinition優(yōu)先加載到容器的一個Map里
registerBean方法真實調(diào)用doRegisterBean方法()
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
// 將配置類包裝成AnnotatedGenericBeanDefinition的類型
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
// 是否跳過, @Condition注解(解析改注解類是否需要被注冊在容器里)
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(instanceSupplier);
// 解析bean的范圍侠仇,如request_session纳令、singleton等
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
// 決定系統(tǒng)內(nèi)的BeanName ,如在@Bean注解上用@value或@name等注解帘不,則beanName就是該值,否則返回方法名作為beanName
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 處理bean的通用注解信息,比如bean是否是懶加載,是否被@Primary標(biāo)注苹支,dependsOn是什么,解析出來
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));
}
}
}
// 定制beanDefinition的屬性误阻,比如是否改為lazy-init 是否為primary等
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
// 裝在BeanDefinition的類
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 真正去注冊beanDefinition的地方
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
進入registerBeanDefinition()方法里
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
String beanName = definitionHolder.getBeanName();
// BeanDefinitionRegistry類是一個接口沐序,里面定義了一些通用的方法,比如registerBeanDefinition堕绩,
// removeBeanDefinition等方法策幼,就是對一個beanDefinition的增刪改查
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
// 注冊該bean的別名
registry.registerAlias(beanName, alias);
}
}
}
最后的registerBeanDefinition的最終實現(xiàn)是在DefaultListableBeanFactory里面實現(xiàn)的
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
// 注冊前驗證bean是否合法
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
BeanDefinition oldBeanDefinition;
// 現(xiàn)在裝在beanDefinition的map里面查看是否有舊的definition信息
oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (this.logger.isWarnEnabled()) {
this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(oldBeanDefinition)) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
// 覆蓋之前的BeanDefinition信息
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
// beanDefinitionMap里面沒有當(dāng)前要注冊的definition信息,所以開始將這個信息put進去
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (oldBeanDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
最終將beanDefinition裝在容器維護的一個beanDefinitionMap里面