第四章 Spring進階-自動掃描和管理Bean

第四章 Spring進階-自動掃描和管理Bean

徒弟:師傅,好累呀,我今天配置了幾十個bean,快不行啦!

師傅:up,沒有那麼弱吧?先磨鍊一下,再告訴你祕訣!

徒弟問,要自己配置bean,如果有成千上萬的類,豈不是要他配置到死翹翹,師傅,有沒有其他辦法管理bean呀,如果確定需要配置一個bean,最好我寫完接口的實現類,就配置完畢,別再讓我折騰配置文件了?

其實,到目前爲止大多數例子都使用XML來指定配置元數據,這些元數據會生成Spring容器中的每個BeanDefinition。 即使上一章A利用@Resource解決了注入問題, bean還是需要在xml中顯式定義。因此本章會介紹一種方法,通過掃描classpath並匹配過濾器來隱式地檢測候選組件 (candidate components)。

補充:

具體可以參考:參考Spring Framework開發手冊 3.12. 對受管組件的Classpath掃描

徒弟看完文檔之後,立馬醒悟了,做了以下幾步:

1、修改BookServiceImpl,增加, 如圖所示定義:

wps_clip_image1

這個時候提示,需要引入包:

import org.springframework.stereotype.Service;

2徒弟很聰明,同樣修改了DAO

@Service("bookDAO")

public class BookDAOImpl implements BookDAO

2、修改beans.xml

<!--&lt;context:annotation-config/>

 <bean id="bookService" class="com.netease.lee.service.impl.BookServiceImpl"/>

 <bean id="bookDAO" class="com.netease.lee.dao.impl.BookDAOImpl"/>

 --&gt;

 <context:component-scan base-package="com.netease.lee"/>

3、運行測試用例,居然成功了:

wps_clip_image2

這裏需要更正一個概念,第二步中@Service("bookDAO")

根據Spring Framework中的建議:

從Spring 2.0開始,引入了@Repository註解, 用它來標記充當儲存庫(又稱 Data Access Object或DAO)角色或典型的類。

Spring 2.5引入了更多典型化註解(stereotype annotations): @Component@Service@Controller@Component是所有受Spring管理組件的通用形式; 而@Repository@Service@Controller則是@Component的細化, 用來表示更具體的用例(例如,分別對應了持久化層、服務層和表現層)。也就是說, 你能用@Component來註解你的組件類, 但如果用@Repository@Service@Controller來註解它們,你的類也許能更好地被工具處理,或與切面進行關聯。 例如,這些典型化註解可以成爲理想的切入點目標。當然,在Spring Framework以後的版本中, @Repository@Service@Controller也許還能攜帶更多語義。如此一來,如果你正在考慮服務層中是該用 @Component還是@Service, 那@Service顯然是更好的選擇。同樣的,就像前面說的那樣, @Repository已經能在持久化層中進行異常轉換時被作爲標記使用了。

因此,修改爲:

@Repository("bookDAO")

public class BookDAOImpl implements BookDAO

這樣子,思路更加清晰了,其他開發人員一看,就知道意思了。

徒弟檢查了配置文件:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"      

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context

           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 <context:component-scan base-package="com.netease.lee"/>

</beans>

發覺,瘦身成功!終於可以很爽快了!

0

收藏

jooben

127篇文章,48W+人氣,11粉絲

Ctrl+Enter 發佈

發佈

取消

0

分享
jooben
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章