Spring
中 @Component
和 @Bean
区别
文章目录
1. 用途不同
@Component
用于标识一个普通的类,@Bean
用于配置类里面,在方法上面声明和配置 Bean
对象
2.使用方式不同
@Component
是类级别的注解,Spring
可以扫描到配置此注解的这些类并把他们注入到 SpringIOC
容器中,@Bean
是修饰在方法上的,表示此方法返回一个 Bean
对象注入到 SpringIOC
容器中。
@Component
使用示例
@Component
public class OrderService {
}
但是在spring
中通常@Component
注解通常要配合@ComponentScan
实现注册的功能
@ComponentScan("指定@Component注解所在的包路径")
public class AppConfig {
}
@Bean
使用示例
@Configuration
public class AppConfig {
@Bean
public OrderService orderService1(){
return new OrderService();
}
}
@Bean
需要在配置类中使用,即类上需要加上@Configuration
注解,然后在配置类中使用一个方法定义bean
是如何创建的
3. 控制权不同
@Component
修饰的类是由Spring框架
统一管理和创建的,而 @Bean
允许开发人员手动控制 Bean
的创建和配置
4. 灵活性不同
@Bean
注解比@Component
注解灵活,我们可以按需注册需要的bean
,很多场景我们只能通过@Bean
来注册bean
,比如引入第三方库中的类需要装配到spring
容器中。
参考文献
-
Spring中@Component注解和@Bean的区别是什么-CSDN博客
-
Spring中@Component和@Bean的区别_spring bean和component-CSDN博客