引言
最近使用Spring,發現有很多依賴注入的內容,特別是DAO,百思不得其解,后來才知道是Spring的依賴注入。Spring可以批量將一個目錄下所有的植入@Repository 注解或者@Service 注解的組件類一次性掃描出來。
事例
<?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:annotation-config /> <context:component-scan base-package=”com.eric.spring”> </beans>
簡單解釋一下:
1、annotation-config是對標記了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的類進行對應的操作使注解生效。
2、base-package為需要掃描的包(含所有子包),負責掃描那些類有注解。
官方解釋
下面是引用spring framework開發手冊中的一段話:
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已經能在持久化層中進行異常轉換時被作為標記使用了。
接下來詳細說明一下@Component、@Service、@Repository和@Controller的區別
@Component 泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
@Service 用於標注業務層組件
@Controller 用於標注控制層組件(如struts中的action)
@Repository 用於標注數據訪問組件,即DAO組件
引用組件
在需要組件的地方,使用如下代碼即可引用
@Resource private ElevenDao elevenDao; //ElevenDao類是需要引用的組件