@Component、@Controller、@Service、@Repository、@Configuration这几个自动注入的注解,能实现自动注入基础都是@Component。出现了这么多@Component的后继,是因为业务应用场景复杂,除了规范不一,加载原理可能也有差别。这里先看下使用规范。
一、@Component
1、介绍
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
@Component
注解是 Spring 框架中的一个核心注解,用于标记一个类是一个 Spring 的组件(Bean),并且该类的实例会被自动注册到 Spring 的应用上下文中。具体来说,@Component
注解告诉 Spring 容器该类是一个 Spring Bean,Spring 会在启动时自动创建该类的实例(即new一个对象),并将其管理;
2、使用注意
(1)interface
接口本身是不能被实例化的,它只能被实现。因此,不能将 @Component及其派生
注解应用于接口。在接口上使用 @Component
会报错,因为接口没有实例化的意义。
@Component
public interface MyService {
void performService();
}
(2)抽象类
可以使用。
虽然抽象类可以有部分实现,但是它不能直接被实例化。如果在抽象类上使用 @Component及其派生
注解,Spring 也不会直接创建该抽象类的实例。
但如果某个具体的子类实现了该抽象类并标注了 @Component
,Spring 会实例化该子类并管理它,以下Spring 会实例化 ConcreteService
类,而不是 MyAbstractService