refresh方法中,調用注解解析bean的loadBeanDefinitions方法如下:
public class AnnotationConfigWebApplicationContext extends AbstractRefreshableWebApplicationContext
implements AnnotationConfigRegistry
//載入注解Bean定義資源
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
//為容器設定注解Bean定義讀取器
AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
//為容器設定類路徑Bean定義掃描器
ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);
//擷取容器的Bean名稱生成器
BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
//為注解Bean定義讀取器和類路徑掃描器設定Bean名稱生成器
if (beanNameGenerator != null) {
reader.setBeanNameGenerator(beanNameGenerator);
scanner.setBeanNameGenerator(beanNameGenerator);
beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
}
//擷取容器的作用域元資訊解析器
ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
//為注解Bean定義讀取器和類路徑掃描器設定作用域元資訊解析器
if (scopeMetadataResolver != null) {
reader.setScopeMetadataResolver(scopeMetadataResolver);
scanner.setScopeMetadataResolver(scopeMetadataResolver);
}
if (!this.annotatedClasses.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Registering annotated classes: [" +
StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
}
reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
}
if (!this.basePackages.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Scanning base packages: [" +
StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
}
scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
}
//擷取容器定義的Bean定義資源路徑
String[] configLocations = getConfigLocations();
//如果定位的Bean定義資源路徑不為空
if (configLocations != null) {
for (String configLocation : configLocations) {
try {
//使用目前容器的類加載器加載定位路徑的位元組碼類檔案
Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
if (logger.isInfoEnabled()) {
logger.info("Successfully resolved class for [" + configLocation + "]");
}
reader.register(clazz);
}
catch (ClassNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not load class for config location [" + configLocation +
"] - trying package scan. " + ex);
}
//如果容器類加載器加載定義路徑的Bean定義資源失敗
//則啟用容器類路徑掃描器掃描給定路徑包及其子包中的類
int count = scanner.scan(configLocation);
if (logger.isInfoEnabled()) {
if (count == 0) {
logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
}
else {
logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
}
}
}
}
}
}
1.1.先看loadBeanDefinitions中的register方法:
loadBeanDefinitions:1 register
//注冊多個注解Bean定義類
public void register(Class<?>... annotatedClasses) {
for (Class<?> annotatedClass : annotatedClasses) {
registerBean(annotatedClass);
}
}
//注冊一個注解Bean定義類
public void registerBean(Class<?> annotatedClass) {
doRegisterBean(annotatedClass, null, null, null);
}
//Bean定義讀取器向容器注冊注解Bean定義類
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
//根據指定的注解Bean定義類,建立Spring容器中對注解Bean的封裝的資料結構
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(instanceSupplier);
//解析注解Bean定義的作用域,若@Scope("prototype"),則Bean為原型類型;
//若@Scope("singleton"),則Bean為單态類型
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
//為注解Bean定義設定作用域
abd.setScope(scopeMetadata.getScopeName());
//為注解Bean定義生成Bean名稱
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
//處理注解Bean定義中的通用注解
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
//如果在向容器注冊注解Bean定義時,使用了額外的限定符注解,則解析限定符注解。
//主要是配置的關于autowiring自動依賴注入裝配的限定條件,即@Qualifier注解
//Spring自動依賴注入裝配預設是按類型裝配,如果使用@Qualifier則按名稱
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
//如果配置了@Primary注解,設定該Bean為autowiring自動依賴注入裝//配時的首選
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
//如果配置了@Lazy注解,則設定該Bean為非延遲初始化,如果沒有配置,
//則該Bean為預執行個體化
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
//如果使用了除@Primary和@Lazy以外的其他注解,則為該Bean添加一
//個autowiring自動依賴注入裝配限定符,該Bean在進autowiring
//自動依賴注入裝配時,根據名稱裝配限定符指定的Bean
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
//建立一個指定Bean名稱的Bean定義對象,封裝注解Bean定義類資料
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
//根據注解Bean定義類中配置的作用域,建立相應的代理對象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//向IOC容器注冊注解Bean類定義對象
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
看一下register中的doRegisterBean方法:
doRegisterBean :1
public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver
//解析注解Bean定義類中的作用域元資訊
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
//從注解Bean定義類的屬性中查找屬性為”Scope”的值,即@Scope注解的值
//annDef.getMetadata().getAnnotationAttributes方法将Bean
//中所有的注解和注解的值存放在一個map集合中
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType);
//将擷取到的@Scope注解的值設定到要傳回的對象中
if (attributes != null) {
metadata.setScopeName(attributes.getString("value"));
//擷取@Scope注解中的proxyMode屬性值,在建立代理對象時會用到
ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
//如果@Scope的proxyMode屬性為DEFAULT或者NO
if (proxyMode == ScopedProxyMode.DEFAULT) {
//設定proxyMode為NO
proxyMode = this.defaultProxyMode;
}
//為傳回的中繼資料設定proxyMode
metadata.setScopedProxyMode(proxyMode);
}
}
//傳回解析的作用域元資訊對象
return metadata;
}
doRegisterBean:2
//處理注解Bean定義中的通用注解
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {
processCommonDefinitionAnnotations(abd, abd.getMetadata());
}
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
//如果Bean定義中有@Lazy注解,則将該Bean預執行個體化屬性設定為@lazy注解的值
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
else if (abd.getMetadata() != metadata) {
lazy = attributesFor(abd.getMetadata(), Lazy.class);
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
}
//如果Bean定義中有@Primary注解,則為該Bean設定為autowiring自動依賴注入裝配的首選對象
if (metadata.isAnnotated(Primary.class.getName())) {
abd.setPrimary(true);
}
//如果Bean定義中有@ DependsOn注解,則為該Bean設定所依賴的Bean名稱,
//容器将確定在執行個體化該Bean之前首先執行個體化所依賴的Bean
AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
if (dependsOn != null) {
abd.setDependsOn(dependsOn.getStringArray("value"));
}
if (abd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
AnnotationAttributes role = attributesFor(metadata, Role.class);
if (role != null) {
absBd.setRole(role.getNumber("value").intValue());
}
AnnotationAttributes description = attributesFor(metadata, Description.class);
if (description != null) {
absBd.setDescription(description.getString("value"));
}
}
}
-----------------------------------------
doRegisterBean:3
//根據注解Bean定義類中配置的作用域,建立相應的代理對象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
static BeanDefinitionHolder applyScopedProxyMode(
ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
//擷取注解Bean定義類中@Scope注解的proxyMode屬性值
ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
//如果配置的@Scope注解的proxyMode屬性值為NO,則不應用代理模式
if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
return definition;
}
//擷取配置的@Scope注解的proxyMode屬性值,如果為TARGET_CLASS
//則傳回true,如果為INTERFACES,則傳回false
boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
//為注冊的Bean建立相應模式的代理對象
return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}
-----------------------------------------
doRegisterBean:4
//向IOC容器注冊注解Bean類定義對象
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
//将解析的BeanDefinitionHold注冊到容器中
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
//擷取解析的BeanDefinition的名稱
String beanName = definitionHolder.getBeanName();
//向IOC容器注冊BeanDefinition
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
//如果解析的BeanDefinition有别名,向容器為其注冊别名
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
----------------------------------------------------------------
loadBeanDefinitions:2
int count = scanner.scan(configLocation);
//調用類路徑Bean定義掃描器入口方法
public int scan(String... basePackages) {
//擷取容器中已經注冊的Bean個數
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
//啟動掃描器掃描給定包
doScan(basePackages);
// Register annotation config processors, if necessary.
//注冊注解配置(Annotation config)處理器
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
//傳回注冊的Bean個數
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
scan:1
//啟動掃描器掃描給定包
doScan(basePackages);
//類路徑Bean定義掃描器掃描給定包及其子包
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
//建立一個集合,存放掃描到Bean定義的封裝類
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
//周遊掃描所有給定的包
for (String basePackage : basePackages) {
//調用父類ClassPathScanningCandidateComponentProvider的方法
//掃描給定類路徑,擷取符合條件的Bean定義
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
//周遊掃描到的Bean
for (BeanDefinition candidate : candidates) {
//擷取Bean定義類中@Scope注解的值,即擷取Bean的作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
//為Bean設定注解配置的作用域
candidate.setScope(scopeMetadata.getScopeName());
//為Bean生成名稱
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
//如果掃描到的Bean不是Spring的注解Bean,則為Bean設定預設值,
//設定Bean的自動依賴注入裝配屬性等
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
//如果掃描到的Bean是Spring的注解Bean,則處理其通用的Spring注解
if (candidate instanceof AnnotatedBeanDefinition) {
//處理注解Bean中通用的注解,在分析注解Bean定義類讀取器時已經分析過
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
//根據Bean名稱檢查指定的Bean是否需要在容器中注冊,或者在容器中沖突
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
//根據注解中配置的作用域,為Bean應用相應的代理模式
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
//向容器注冊掃描到的Bean
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
//掃描給定類路徑的包
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
return scanCandidateComponents(basePackage);
}
}
findCandidateComponents 1
private Set<BeanDefinition> addCandidateComponentsFromIndex(CandidateComponentsIndex index, String basePackage) {
//建立存儲掃描到的類的集合
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
Set<String> types = new HashSet<>();
for (TypeFilter filter : this.includeFilters) {
String stereotype = extractStereotype(filter);
if (stereotype == null) {
throw new IllegalArgumentException("Failed to extract stereotype from "+ filter);
}
types.addAll(index.getCandidateTypes(basePackage, stereotype));
}
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (String type : types) {
//為指定資源擷取中繼資料讀取器,元資訊讀取器通過彙編(ASM)讀//取資源元資訊
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(type);
//如果掃描到的類符合容器配置的過濾規則
if (isCandidateComponent(metadataReader)) {
//通過彙編(ASM)讀取資源位元組碼中的Bean定義元資訊
AnnotatedGenericBeanDefinition sbd = new AnnotatedGenericBeanDefinition(
metadataReader.getAnnotationMetadata());
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Using candidate component class from index: " + type);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + type);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because matching an exclude filter: " + type);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
if (isCandidateComponent(sbd)) {
//判斷元資訊讀取器讀取的類是否符合容器定義的注解過濾規則
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
//如果讀取的類的注解在排除注解過濾規則中,傳回false
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
//如果讀取的類的注解在包含的注解的過濾規則中,則傳回ture
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}
//如果讀取的類的注解既不在排除規則,也不在包含規則中,則傳回false
return false;
}
findCandidateComponents: 2
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (Resource resource : resources) {
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
if (resource.isReadable()) {
try {
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setResource(resource);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Identified candidate component class: " + resource);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + resource);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not matching any filter: " + resource);
}
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not readable: " + resource);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}