spring在啟動時會自己把bean(java組件)注冊到ioc容器里,實現控制反轉,在開發人員使用spring開發應用程序時,你是看不到new關鍵字的,所有對象都應該從容器里獲得,它們的 生命周期 在放入容器時已經確定!
下面說一下三種注冊bean的方法
- @componentscan
- @bean
- @import
@componentscan注冊指定包里的bean
spring容器會掃描@componentscan配置的包路徑,找到標記@component注解的類加入到spring容器。
我們經常用到的類似的(注冊到ioc容器)注解還有如下幾個:
- @configuration:配置類
- @controller :web控制器
- @repository :數據倉庫
- @service:業務邏輯
下面代碼完成了emaillogserviceimpl這個bean的注冊,當然也可以放在@bean里統一注冊,需要看@bean那一節里的介紹。
1
2
3
4
5
6
7
8
9
10
|
@component public class emaillogserviceimpl implements emaillogservice { private static final logger logger = loggerfactory.getlogger(emaillogserviceimpl. class ); @override public void send(string email, string message) { assert .notnull(email, "email must not be null!" ); logger.info( "send email:{},message:{}" , email, message); } } |
@bean注解直接注冊
注解@bean被聲明在方法上,方法都需要有一個返回類型,而這個類型就是注冊到ioc容器的類型,接口和類都是可以的,介于面向接口原則,提倡返回類型為接口。
下面代碼在一個@configuration注解的類中,同時注冊了多個bean。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@configuration public class logserviceconfig { /** * 擴展printlogservice行為,直接影響到logservice對象,因為logservice依賴于printlogservice. * * @return */ @bean public printlogservice printlogservice() { return new printlogserviceimpl(); } @bean public emaillogservice emaillogservice() { return new emaillogserviceimpl(); } @bean public printlogservice consoleprintlogservice() { return new consoleprintlogservice(); } } |
@import注冊bean
這種方法最為直接,直接把指定的類型注冊到ioc容器里,成為一個java bean,可以把@import放在程序的八口,它在程序啟動時自動完成注冊bean的過程。
1
2
3
4
|
@import ({ logservice. class ,printservice. class }) public class registrybean { } |
spring之所以如何受歡迎,我想很大原因是它自動化注冊和自動化配置這一塊的設計,確實讓開發人員感到非常的自如,.net里也有類似的產品,像近幾年比較流行的abp框架,大叔自己也寫過類似的lind框架,都是基于自動化注冊和自動化配置的理念。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/lori/p/10418271.html