相同點:
@Component爲@Service、@Controller、@Repository的元註解,四個實現功能是一樣的
不同點爲區分業務層:
- @Component 業務特殊組件層,如handler類
- @Controller 業務控制層
- @Service 業務邏輯層
- @Repository 業務資源層
@Component用來做什麼?
被@Component標註的類被視爲自動檢測的候選者;
@Component何時用?
- 在SpringBoot中使用@ComponentScan來自動檢測定位指定包下的候選者,將掃描到的候選者進行解析載入(將用戶定義好的Bean抽象爲IOC內部的數據結構BeanDefinition,注入到HashMap對象中),然後通過BeanDefinitionRegistry接口將載入的BeanDefinition註冊到IOC容器中。
- Spring IOC設計時,Bean定義的定位載入註冊和依賴注入兩個獨立的過程。依賴注入爲應用第一次通過getBean向容器索取Bean的時候。或通過類註解@Lazy(false),使Bean的依賴注入再IOC的初始化時預先完成(自己項目中未使用,看源碼得來的,有需要的時候需要試下)。
Spring-context 5.0.4源碼
@Component
package org.springframework.stereotype;
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.stereotype.Indexed
public @interface Component {
java.lang.String value() default "";
}
@Service
package org.springframework.stereotype;
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
//@Component做爲元註解
@org.springframework.stereotype.Component
public @interface Service {
//此註解指定當前屬性和父類的value屬性關聯綁定
@org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class)
java.lang.String value() default "";
}