注:annotation-based configuration是一把雙刃劍,與xml-based configuration相比,有利有弊,其中利弊不在本文讨論的範圍内,不再多說,僅提醒各位根據自身的需要謹慎選擇。
使用Annotaion似乎成了時尚和趨勢,spring2.5提供了一些Annotation,使開發者可以簡化我們的配置檔案。本文簡單闡述一下spring2.5中的Annotation是如何使用的,不做深層次的研究。
一、配置檔案可以簡化到什麼程度?
使用annotation以前,我們要在xml配置檔案中配置每一個我們用spring管理的bean,有十個要寫十個,有一百個要寫一百個......
使用annotation之後,及至情況下,我們可以一個都bean都不寫,那麼我們的配置檔案就要寫成下面的樣子:
<?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" default-autowire="byName" default-lazy-init="true">
<context:annotation-config />
<context:component-scan base-package="org.example">
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
看看,上面沒有一個<bean>标簽吧!下面簡單解釋一下下面的配置:
1) <beans>标簽裡面,以前我們用DTD,現在我們用的是XMLSchema-style,具體含義本文不講了(本文是“淺析”教程嘛)
2) <context:annotation-config />表示,我們要使用Annotation-based的bean管理方式。
3) <context:component-scan base-package="org.example">表示org.example包下的一些類使用Annotation-based的bean管理方式,換句話說就是在這個包下的Annotation才會起作用,其他包下的沒用。
4) <context:include-filter和<context:exclude-filter就是用正規表達式來include和exclude指定包(就是org.example)想的一下bean。
二、怎麼什麼聲明一個spring管理的bean?怎麼注入bean?
聲明:在bean上加注釋@Component,例:
package org.example;
@Component("sampleBean")
public class SampleBean{
//......
}
注入:在field,seter等上加注釋@Autowired,例:
public class SampleBeanInjection{
private SampleBean sampleBean;
@Autowired
public setSampleBean(SampleBean sampleBean){
如上的例子不是很恰當,明眼人見諒。
三、有哪些Annotation可用?
在org.springframework.stereotype包下,有用于聲明bean的Annotation:
Component
Controller
Repository
Service
在org.springframework.beans.factory.annotation包下,有用于注入bean的Annotation:
Autowired
Qualifier
Required
在JSR-250的規範中(即j2ee的javax.annotation包下),有@Resource用來注入bean,其功能與@Autowired相似。