鍍金池/ 問(wèn)答/Java/ spring掃描組件時(shí)會(huì)掃描該組件的父類(lèi)及接口么?有沒(méi)有明確的文檔說(shuō)明?

spring掃描組件時(shí)會(huì)掃描該組件的父類(lèi)及接口么?有沒(méi)有明確的文檔說(shuō)明?

如題。
如題。
如題。

回答
編輯回答
葬愛(ài)

這里有非常好的例子展示spring掃描的范圍設(shè)定
符合以下條件的會(huì)被掃描并創(chuàng)建bean

  • 類(lèi)有@Component注解
  • 且包名包含在@ComponentScan注解范圍內(nèi)
  • 或包含在@ComponentScan.Filter范圍內(nèi)

如果子類(lèi)符合條件,但父類(lèi)沒(méi)有包含在掃描范圍內(nèi), 子類(lèi)會(huì)創(chuàng)建,但父類(lèi)不會(huì)創(chuàng)建, 因?yàn)椴环?code>instanceof條件,即不能說(shuō)父類(lèi)子類(lèi)
如果父類(lèi)被創(chuàng)建, 子類(lèi)有@Component注解,但不在指定Filter范圍內(nèi),也會(huì)創(chuàng)建,因?yàn)榉?code>instanceof條件,因?yàn)樽宇?lèi)一定是父類(lèi)

@Component注解沒(méi)有繼承關(guān)系(@Inherited), 所以想被創(chuàng)建必須首先要有這個(gè)注解才行.
或創(chuàng)建你自己的可繼承的注解過(guò)的接口.

如:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component 
@Inherited
public @interface BusinessService {
}
2018年4月3日 14:15
編輯回答
吃藕丑

另外 如果是spring boot的其實(shí)可以自己測(cè)試 看下結(jié)果的 http://ip:port/beans

2017年7月22日 16:34
編輯回答
淺淺

自問(wèn)自答,提出問(wèn)題第二天就已通過(guò)跟蹤源碼找到答案,說(shuō)說(shuō)結(jié)果給后人以經(jīng)驗(yàn).
為什么會(huì)有這樣的問(wèn)題,來(lái)自于springcloud feign 遠(yuǎn)程調(diào)用場(chǎng)景,controller繼承了api service,在service的方法上定義RequestMapping,controller中不定義,spring同樣能掃描到,完成請(qǐng)求地址與方法的映射,這個(gè)過(guò)程蹊蹺的地方在于,接口中定義的注解并不會(huì)被類(lèi)繼承,其唯一可以識(shí)別到的方式就是 掃描父類(lèi),但是一般似乎從來(lái)沒(méi)這么用過(guò),在關(guān)于spring源碼解析的文章當(dāng)中也很少有提及掃描組件會(huì)去查找父類(lèi)中的注解,帶著問(wèn)題去跟蹤源碼,發(fā)現(xiàn),在掃描組件過(guò)程中反復(fù)調(diào)用了 這么一個(gè)類(lèi)AnnotatedElementUtils,其中的方法searchWithGetSemantics,語(yǔ)義化搜索,什么叫語(yǔ)義化搜索,該類(lèi)的注釋已明確給出了答案.
` * <p>{@code AnnotatedElementUtils} defines the public API for Spring's

  • meta-annotation programming model with support for annotation attribute
  • overrides. If you do not need support for annotation attribute
  • overrides, consider using {@link AnnotationUtils} instead. * <p>Find semantics are much more exhaustive, providing
  • get semantics plus support for the following:

*

  • <ul>
  • <li>Searching on interfaces, if the annotated element is a class
  • <li>Searching on superclasses, if the annotated element is a class
  • <li>Resolving bridged methods, if the annotated element is a method
  • <li>Searching on methods in interfaces, if the annotated element is a method
  • <li>Searching on methods in superclasses, if the annotated element is a method
  • </ul>`
2018年6月7日 18:23