@Bean 和@ Component的區別


  1. @Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
  2. @Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
  3. @Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.
  4. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
  5. We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
  6. @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

 

1. component :  1  利用spring 類路徑掃描,

        2. 寫在類上,和類定義不分離。 

        3. 不需要配合 @configuration注解

2. Bean :  .當類不受spring控制的時候,寫一個方法,返回某個不受spring控制的類的對象。 這樣就能在spring里注入一個bean。

      配合configuration注解

 參考:https://stackoverflow.com/questions/10604298/spring-component-versus-bean       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM