Spring註解開發(學習筆記)

Spring註解開發
優點:方便、簡單、快捷
缺點:第三方jar包,沒法給他們添加@Component註解,沒法用
IOC(控制反轉)
不使用new關鍵字進行實例化對象,而是通過反射機制使用全限定類名進行實例化,實現細節由spring完成。

初始化環境
在maven項目下,在pom.xml項目對象管理文件中添加spring項目所需的依賴。
spring的核心依賴(上下文依賴)

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.13.RELEASE</version>
</dependency>
spring的測試依賴,需要導入junit依賴(可選)
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>RELEASE</version>
		<scope>test</scope>
	</dependency>

log4j日誌依賴(可選),需要寫配置文件
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.12</version>
	</dependency>

spring註解
工作機制
當使用
ApplicationContextapplicationContext=newAnnotationConfigApplicationContext(配置類名.class);初始化上下文環境時,
被@ComponentScan掃描到的@Component會實例化
Object object=applicationContext.getBean(Object.class);獲取被spring創建好的對象

@Configuration:配置類,一般該類是@ComponentScan
@ComponentScan:掃描到所有@Component類,ComponentScan只能掃描到當前包或者子包中的@Component,可以在註解後面添加包名擴大它的掃描範圍
	@Configuration
	@ComponentScan("pakagename") 
	publicclassAppConfig{
	}
@Component:組件,被@ComponentScan發現掃描到,從而使spring上下文發現,可以由spring通過反射機制進行實例化對象,面向接口開發時應在實現類上註解
@Autowired:自動裝配,一般修飾成員變量(便捷)、set方法、有參構造方法(效率高)、或者自定義方法(會自動執行,比set方法更加方便一些),它會根據類名自動獲取spring創建好的對象自動初始化

required關鍵字:spring默認使必須裝配@Autowired修飾的對象,該對象的類不存在或者不是@Component時,裝配失敗會報錯,如果自動裝配是非必須的,則需要在@Autowired註解後面添加required=false;如@Autowired(required=false),默認爲true。使用required關鍵字時需要進行非空檢查,否則會發生空指針異常。

面向接口開發時,一般是實現接口,而不是實現類,如果一個接口出現多個實現類的話,那麼應該爲接口裝配哪個類的對象,解決衝突呢?
1、使用@Primary來修飾首選bean,但是有時候也會造成衝突
2、在@Component上添加@Qualifier("id")(或者直接使用@Component"id"),在裝配的對象的時候也用添加註解@Qualifier("id"),就可以解決實現類的衝突了
3、更簡單的,可以不用在@Component上添加id,那麼默認使用類名作爲id(類名首字母小寫),然後再使用註解@Qualifier("id")
以上方式爲Spring的標準解決方案,下面爲java的標準解決方案
使用@Resource(name="id")註解來代替 @Autowired 與 @Qualifier("id")兩個註解

在實際開發三層架構中:
@Repository在Dao層中可以代替@Component
@Service在service層中可以代替@Component
@Controller在Web層中可以代替@Component
它們具有同樣的功能,但是針對性更強。

註解開發總結

定義配置  
@Configuration
@ComponentScan

定義組件
@Component
@Autowired
@Autowired(required=false)

自動裝配歧義性
@Primary
@Qualifier
@Resource

分層架構中定義組件
@Controller
@Service
@Repository

Spring測試環境
@Runwith
@ContextConfiguration     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章