SpringMVC四大注解
- Component
通用標注,在不清楚使用哪個注解的時候,可以使用Component通用注解
- Controller
標注web請求控制器
- Service
標注Service層的服務
- Repository
標注DAO層的數據訪問
四大注解都是類級別的,可以不帶任何參數,也可以帶一個參數,代表bean名字,在進行注入的時候就可以通過名字進行注入了。
bean的自動載入
在SpringMVC的配置文件中,通過context:component-scan使注解生效。這樣就可以代替在web.xml中配置bean,自動實現bean的載入。例子:
<context:component-scan base-package="com.studySpringMVC.*"> <context:include-filter type="annotation" expression="com.studySpringMVC.service"/> <context:exclude-filter type="annotation" expression=" com.studySpringMVC.service "/> </context:component-scan>
context:include-filter定義需要掃描的包,context:exclude-filter定義不掃描的包,在配置時,兩個標簽的expression值不能設置成相同
type屬性值有5個
Filter Type | Examples Expression | Description |
annotation | org.example.SomeAnnotation | 符合SomeAnnoation的target class(被四大標注注釋了的類) |
assignable | org.example.SomeClass | 指定class或interface的全名 |
aspectj | org.example..*Service | AspectJ語法 |
regex | org\.example\.Default.* | Regelar Expression |
custom | org.example.MyTypeFilter | Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter |
使用@Resource或@Autowired注解實現注入
@Autowired默認按類型裝配,默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設置它的required屬性為false(如@Autowired(required=false)),如果我們想使用名稱裝配可以結合@Qualifier注解進行使用
@Resource默認按名稱進行裝配,名稱可以通過name屬性進行指定,如果沒有指定name屬性,當注解寫在字段上時,默認按字段名進行名稱查找,如果注解寫在setter方法上,默認取屬性名進行裝配。當找不到與名稱匹配的bean時才按照類型進行裝配。但是需要注意的是,如果name屬性一旦指定,就只會按照名稱進行裝配。推薦使用@Resource,這個注解屬於J2EE,減少了與Spring的耦合