相同点:
@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 "";
}