Spring框架中@Bean和@Component註解的區別
Spring支援多種型別的註解,例如@Component、@Controller、@Service、@Repository和@Bean。所有這些註解都位於org.springframework.stereotype包下。
當應用程式中的類使用上述任何註解進行註解時,在專案啟動期間,Spring會掃描(使用@ComponentScan)每個類並將類的例項注入到IOC容器中。@ComponentScan的另一個作用是執行帶有@Bean註解的方法,並將返回的物件作為bean儲存到IOC容器中。
序號 | 關鍵點 | @Bean | @Component |
---|---|---|---|
1 | 自動檢測 | 它用於顯式宣告單個bean,而不是讓Spring自動宣告。 | 如果任何類使用@Component註解,則它將透過類路徑掃描自動檢測。 |
2 | Spring容器 | 即使類在Spring容器之外,也可以建立Bean | 如果類在Spring容器之外,則無法建立Bean |
3 | 類/方法級別註解 | 它是方法級別註解 | 它是類級別註解 |
4 | @Configuration | 只有當類也使用@Configuration註解時才有效 | 無需 @Configuration註解 |
5 | 用例 | 如果需要基於動態條件的特定實現,則應使用@Bean。 | 無法基於動態條件編寫特定實現 |
@Component示例
@Component public class Pizza{ ........ }
@Bean示例
@Configuration class AppConfiguration{ @Bean public User getUse(){ return new User(); } }
廣告