一文掌握Spring?中?@Component?和?@Bean?區(qū)別(最新推薦)
Spring 中 @Component 和 @Bean 區(qū)別
1. 用途不同
?@Component 用于標識一個普通的類,@Bean用于配置類里面,在方法上面聲明和配置 Bean 對象
Tips:
@Component會告訴Spring,由@Component所修飾的類會被作為組件類,同時Spring要為這個類創(chuàng)建Bean- 告知
spring這個方法會返回一個對象,這個對象需要注冊為Spring上下文(ApplicationContext)中的bean,通常方法體包含了最終產(chǎn)生bean實例的邏輯
2.使用方式不同
? @Component 是類級別的注解,Spring 可以掃描到配置此注解的這些類并把他們注入到 SpringIOC 容器中,@Bean 是修飾在方法上的,表示此方法返回一個 Bean 對象注入到 SpringIOC 容器中。
Tips:但是都能夠在Spring中注冊Bean對象
@Component 使用示例
@Component
public class OrderService {
}但是在spring中通常@Component注解通常要配合@ComponentScan實現(xiàn)注冊的功能
@ComponentScan("指定@Component注解所在的包路徑")
public class AppConfig {
}@Bean 使用示例
@Configuration
public class AppConfig {
@Bean
public OrderService orderService1(){
return new OrderService();
}
}@Bean需要在配置類中使用,即類上需要加上@Configuration注解,然后在配置類中使用一個方法定義bean是如何創(chuàng)建的
3. 控制權(quán)不同
? @Component 修飾的類是由Spring框架 統(tǒng)一管理和創(chuàng)建的,而 @Bean 允許開發(fā)人員手動控制 Bean的創(chuàng)建和配置
4. 靈活性不同
@Bean注解比@Component注解靈活,我們可以按需注冊需要的bean,很多場景我們只能通過@Bean來注冊bean,比如引入第三方庫中的類需要裝配到spring容器中。
參考文獻
Spring中@Component注解和@Bean的區(qū)別是什么
Spring中@Component和@Bean的區(qū)別_spring bean和component
到此這篇關(guān)于Spring 中 @Component 和 @Bean 區(qū)別的文章就介紹到這了,更多相關(guān)Spring @Component 和 @Bean 區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA中已配置阿里鏡像但maven無法下載jar包的問題及解決方法
這篇文章主要介紹了IDEA中已配置阿里鏡像但maven無法下載jar包的問題,本文給大家分享解決方法,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
kafka消費者kafka-console-consumer接收不到數(shù)據(jù)的解決
這篇文章主要介紹了kafka消費者kafka-console-consumer接收不到數(shù)據(jù)的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

