@component加在接口还是实现类上
时间: 2023-08-06 17:07:06 浏览: 199
`@Component` 是 Spring Framework 中的注解,用于声明一个类为组件,以便 Spring 能够自动扫描并将其注册为 Bean。在接口中使用 `@Component` 注解并没有实际意义,因为接口本身并不是一个可实例化的类,也不能直接被 Spring 所管理。
因此,一般情况下我们会将 `@Component` 注解加在实现类上,以标识其为一个可被 Spring 所管理的 Bean。当然,如果你需要在多个实现类之间进行选择,可以使用 `@Qualifier` 注解来进行指定。例如:
```java
public interface MyInterface {
void doSomething();
}
@Component("impl1")
public class MyInterfaceImpl1 implements MyInterface {
// 实现类1的具体实现
}
@Component("impl2")
public class MyInterfaceImpl2 implements MyInterface {
// 实现类2的具体实现
}
@Component
public class MyService {
@Autowired
@Qualifier("impl1")
private MyInterface myInterface;
// 具体的服务实现
}
```
上述例子中,我们在 MyInterfaceImpl1 和 MyInterfaceImpl2 上分别使用了 `@Component` 注解来标识它们为 Spring Bean,并且在 MyService 中使用了 `@Autowired` 和 `@Qualifier` 注解来指定使用哪个实现类。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)