經(jīng)過這篇文章文章,是不是對(duì)@Component?的使用和實(shí)現(xiàn)原理一清二楚了呢,其實(shí)Spring?中還有@Service、@Controller和@Repository?等注解,他們和@Component有什么區(qū)別呢,你知道嗎?
概述
想必@Component注解大家一直在使用,只要類上加上它,就可以被Spring容器管理,那大家有想過它是怎么實(shí)現(xiàn)的嗎?本篇文章就帶領(lǐng)到家揭秘。
注解介紹
用來標(biāo)記的類是一個(gè)“組件”或者說是一個(gè)Bean,Spring會(huì)自動(dòng)掃描標(biāo)記@Component注解的類作為一個(gè)Spring Bean對(duì)象。
注解源碼:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
String value() default "";
}
屬性說明:
- value: 自定義當(dāng)前組件或者說bean的名稱,可以不配置, 不配置的話默認(rèn)為組件的首字母小寫的類名。
元注解說明:
- 該注解只能使用在類,接口、枚舉、其他注解上
- 該注解的生命周期是運(yùn)行時(shí)JVM
- @Indexed?元注解在spring 5.0引入,用于項(xiàng)目編譯打包時(shí),會(huì)在自動(dòng)生成META-INF/spring.components文件,簡歷索引,從而提高組件掃描效率,減少應(yīng)用啟動(dòng)時(shí)間。
注解使用
- 定義Person類,被@Component注解修飾

- 檢查Person類是否在掃描路徑下

- 獲取bean驗(yàn)證


小結(jié): 通過添加@Component能夠?qū)㈩愞D(zhuǎn)為Spring中的Bean對(duì)象,前提是能過夠被掃描到。
原理解析
閱讀源碼,我們查看@Component?注解的源碼,從中可以看到一個(gè)關(guān)鍵的類ClassPathBeanDefinitionScanner,我們可以從這個(gè)類下手,找到切入點(diǎn)。

分析ClassPathBeanDefinitionScanner?類,找到核心方法doscan, 打個(gè)斷點(diǎn),了解整個(gè)調(diào)用鏈路。

具體分析結(jié)果如下:
- SpringBoot?應(yīng)用啟動(dòng)會(huì)注冊(cè)ConfigurationClassPostProcessor這個(gè)Bean,它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor接口,而這個(gè)接口是Spring提供的一個(gè)擴(kuò)展點(diǎn),可以往BeanDefinition Registry中添加BeanDefintion。所以,只要能夠掃描到@Component注解的類,并且把它注冊(cè)到BeanDefinition Registry中即可。

- 關(guān)鍵方法ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry,查找@Component的類,并進(jìn)行注冊(cè)。

- 我們直接跳到是如何查找@Component的類的,核心方法就是ClassPathBeanDefinitionScanner#doScan。
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
// 遍歷多個(gè)掃描目錄,如本例中的com.alvinlkk
for (String basePackage : basePackages) {
// 核心方法查找所有符合條件的BeanDefinition, 該方法后面重點(diǎn)關(guān)注
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
// 遍歷找到的BeanDefinition
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
// 驗(yàn)證BeanDefinition
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
// 注冊(cè)BeanDefinition到registry中
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
- 重點(diǎn)關(guān)注ClassPathBeanDefinitionScanner#findCandidateComponents方法,找出候選的Bean Component。
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
// 判斷組件是否加了索引,打包后默認(rèn)會(huì)有索引,用于加快掃描
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
// 重點(diǎn)查看else邏輯
else {
return scanCandidateComponents(basePackage);
}
}
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
// 解析出需要掃描的路徑,本例是classpath*:com/alvinlkk/**/*.class
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
// 根據(jù)掃描路徑找到所有的Resource
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
// 遍歷掃描路徑
for (Resource resource : resources) {
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
try {
// 解析出掃描到類的元數(shù)據(jù)信息,里面包含了注解信息
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
// 關(guān)鍵方法,判斷是否候選組件
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
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 (FileNotFoundException ex) {
if (traceEnabled) {
logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage());
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
// 判斷是否候選的Bean Component
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
// exclude過濾器,在exclude過濾其中的,會(huì)直接排除掉,返回false
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
// include過濾器, 這里會(huì)看到有AnnotationTypeFilter,注解類型過濾器
for (TypeFilter tf : this.includeFilters) {
// 調(diào)用AnnotationTypeFilter的match方法,來判斷是否滿足條件
if (tf.match(metadataReader, getMetadataReaderFactory())) {
// 下面在進(jìn)行Condition的判斷,就是類上的@Conditional,這里不是重點(diǎn)
return isConditionMatch(metadataReader);
}
}
return false;
}

而這個(gè)AnnotationTypeFilter默認(rèn)是在構(gòu)造函數(shù)中注冊(cè)進(jìn)去的。

小結(jié):
@Component到Spring bean容器管理過程如下:
- 初始化時(shí)設(shè)置了Component類型過濾器;
- 根據(jù)指定掃描包掃描.class文件,生成Resource對(duì)象;
- 解析.class文件并注解歸類,生成MetadataReader對(duì)象;
- 使用第一步的注解過濾器過濾出有@Component類;
- 生成BeanDefinition對(duì)象;
- 把BeanDefinition注冊(cè)到Spring容器。
總結(jié)
經(jīng)過這篇文章文章,是不是對(duì)@Component?的使用和實(shí)現(xiàn)原理一清二楚了呢,其實(shí)Spring?中還有@Service、@Controller和@Repository?等注解,他們和@Component有什么區(qū)別呢,你知道嗎?