第四章 Spring進階-自動掃描和管理Bean
徒弟:師傅,好累呀,我今天配置了幾十個bean,快不行啦!
師傅:up,沒有那麼弱吧?先磨煉一下,再告訴你秘訣!
徒弟問,要自己配置bean,如果有成千上萬的類,豈不是要他配置到死翹翹,師傅,有沒有其他辦法管理bean呀,如果确定需要配置一個bean,最好我寫完接口的實作類,就配置完畢,别再讓我折騰配置檔案了?
其實,到目前為止大多數例子都使用XML來指定配置中繼資料,這些中繼資料會生成Spring容器中的每個BeanDefinition。 即使上一章A利用@Resource解決了注入問題, bean還是需要在xml中顯式定義。是以本章會介紹一種方法,通過掃描classpath并比對過濾器來隐式地檢測候選元件 (candidate components)。
補充:
具體可以參考:參考Spring Framework開發手冊 3.12. 對受管元件的Classpath掃描
徒弟看完文檔之後,立馬醒悟了,做了以下幾步:
1、修改BookServiceImpl,增加, 如圖所示定義:
<a href="http://jooben.blog.51cto.com/attachment/201005/6/253727_1273123875VHEm.png"></a>
這個時候提示,需要引入包:
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、運作測試用例,居然成功了:
<a href="http://jooben.blog.51cto.com/attachment/201005/6/253727_1273123875huNk.png"></a>
這裡需要更正一個概念,第二步中@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")
這樣子,思路更加清晰了,其他開發人員一看,就知道意思了。
徒弟檢查了配置檔案:
<?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">
</beans>
發覺,瘦身成功!終于可以很爽快了!
本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/311069