摘自:https://www.jianshu.com/p/3fbfbb843b63
最近翻了一下Spring In Action,看完前三章發現@Bean和@Component用得挺多,不過對這兩者的區別不是很清楚,書中也沒有詳細介紹。
Google了一下,發現一篇文章寫得不錯,不過是純英文的:http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/
下面是看過上面文章之后自己的一些理解:
首先我們看看這兩個注解的作用:
-
@Component注解表明一個類會作為組件類,並告知Spring要為這個類創建bean。
-
@Bean注解告訴Spring這個方法將會返回一個對象,這個對象要注冊為Spring應用上下文中的bean。通常方法體中包含了最終產生bean實例的邏輯。
兩者的目的是一樣的,都是注冊bean到Spring容器中。
@Component(@Controller、@Service、@Repository)通常是通過類路徑掃描來自動偵測以及自動裝配到Spring容器中。
而@Bean注解通常是我們在標有該注解的方法中定義產生這個bean的邏輯。
舉個栗子:
@Controller //在這里用Component,Controller,Service,Repository都可以起到相同的作用。 @RequestMapping(″/web/controller1″) public class WebController { ..... }
而@Bean的用途則更加靈活
當我們引用第三方庫中的類需要裝配到Spring容器時,則只能通過@Bean來實現
舉個例子:
public class WireThirdLibClass { @Bean public ThirdLibClass getThirdLibClass() { return new ThirdLibClass(); } }
再舉個只能用@Bean的例子:
@Bean public OneService getService(status) { case (status) { when 1: return new serviceImpl1(); when 2: return new serviceImpl2(); when 3: return new serviceImpl3(); } }
以上這個例子是無法用Component以及其具體實現注解(Controller、Service、Repository)來實現的。
總結:@Component和@Bean都是用來注冊Bean並裝配到Spring容器中,但是Bean比Component的自定義性更強。可以實現一些Component實現不了的自定義加載類。
作者:jasperchen
鏈接:https://www.jianshu.com/p/3fbfbb843b63