@Component 通常是通过路径扫描来自动侦测以及自动装配到 Spring 容器中(我们可以使用 @ComponentScan 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。
@Component是一个通用的 Spring 容器管理的单例 bean 组件。
这里会引申几个问题。
1.@Component 和 @Bean 的区别是什么?
- 作用对象不同:@Component 注解作用于类,而 @Bean 注解作用于方法、
- @Component 通常是通过路径扫描来自动侦测以及自动装配到 Spring 容器中(我们可以使用 @ComponentScan 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。@Bean 注解通常是我们在标有该注解的方法中定义产生这个 bean,@Bean 告诉了 Spring 这是某个类的实例,当我们需要用它的时候还给我。
- @Bean 注解比 @Component 注解的自定义性更强,而且很多地方我们只能通过 @Bean 注解来注册 bean。比如当我们引用第三方库中的类需要装配到 Spring 容器时,只能通过 @Bean 来实现。
@Bean 注解使用示例:
@Configuration
public class ConfigurationDemo {
@Bean
public DemoService demoService() {
return new demoServiceImpl();
}
}
@Component 注解使用示例:
@Component
public class VulnerabilityFileServiceImpl implements VulnerabilityFileService {
..
}
当你的一个类被@Component 所注解,那么就意味着同样可以用@Repository, @Service, @Controller 来替代它,但是最好还是根据具体功能去使用对应功能注解。
2.@Component 和 @Configuration 的区别是什么?
- 调用@Configuration类中的@Bean注解的方法,返回的是同一个示例;
- 而调用@Component类中的@Bean注解的方法,返回的是一个新的实例。
- @Configuration注解本质上还是@Component,因此 < context:component-scan/> 或者 @ComponentScan 都能处理@Configuration注解的类。
3.扩展注解:
- @Component :通用的注解,可标注任意类为 Spring 的组件。如果一个 Bean 不知道属于哪个层,可以使用 @Component 注解标注。
- @Repository :对应持久层即 Dao 层,主要用于数据库相关操作。
- @Service :对应服务层,主要设计一些复杂的逻辑,需要用到 Dao 层。
- @Controller :对应 Spring MVC 控制层,主要用来接受用户请求并调用 Service 层返回数据给前端页面。
- @Configuration :声明该类为一个配置类,可以在此类中声明一个或多个 @Bean 方法。