在 Spring 中,儘管使用XML配置文件可以實現 Bean 的裝配工作,但如果應用中有很多的 Bean 時,會導致XML配置文件過於臃腫,給後續的維護和升級帶來一定的困難. 爲此, Spring 。提供了對Annotation(註解)技術的全面支持。
首先認識一下常用註解的作用:
@Component:用於描述Spring中的Bean,它是一個泛化的概念,僅僅表示一個組件。
@Repository:用於將數據訪問層(DAO)的類標識爲Spring中的Bean。
@Service:用於將業務層中的類標識Spring中的Bean。
@Autowired:用於對Bean的屬性變量、屬性的setter方法及構造方法進行標註,配合對應的註解處理器完成Bean的自動配置工作。
@Resource:其作用與Autowired作用一樣。@Resource中有兩個重要屬性:name和type。Spring將name屬性解析爲Bean實例名稱,type屬性解析爲Bean實例類型。
@Qualifier:與@Autowired註解配合使用,會將默認的按Bean類型裝配修改爲按Bean的實例名稱裝配,Bean的實例名稱由@Qualifier註解的參數指定。
需要注意的是在原來使用基於XML的裝配時的XML配置文件有一些變化,例如:
在使用基於Annotation裝配方式時,XML配置文件代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>