?
本文檔使用 PHP中文網(wǎng)手冊 發(fā)布
Spring有很多自定義的Java 5+注解。
org.springframework.beans.factory.annotation
包
中的@Required
注解能用來標(biāo)記
屬性,將其標(biāo)示為'需要設(shè)置'(例如,一個類中的被注解的(setter)
方法必須配置一個用來依賴注入的值),否則容器會在運(yùn)行時拋出一個Exception
。
演示這個注解用法的最好辦法是給出像下面這樣的范例:
public class SimpleMovieLister { // theSimpleMovieLister
has a dependency on theMovieFinder
private MovieFinder movieFinder; // a setter method so that the Spring container can 'inject' aMovieFinder
@Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually 'uses' the injectedMovieFinder
is omitted... }
希望上面的類定義看起來還算簡單。你必須為所有SimpleMovieLister
類的BeanDefinitions
提供一個值。
讓我們看一個不能通過驗(yàn)證的XML配置范例。
<bean id="movieLister" class="x.y.SimpleMovieLister">
<!-- whoops, no MovieFinder is set (and this property is @Required
) -->
</bean>
運(yùn)行時Spring容器會生成下面的消息(追蹤堆棧的剩下部分被刪除了)。
Exception in thread "main" java.lang.IllegalArgumentException: Property 'movieFinder' is required for bean 'movieLister'.
最后還需要一點(diǎn)(小的)Spring配置來'開啟'這個行為。
簡單注解類的'setter'屬性不足以實(shí)現(xiàn)這個行為。
你還需要一個了解@Required
注解并能適當(dāng)?shù)靥幚硭慕M件。
這個組件就是RequiredAnnotationBeanPostProcessor
類。
這是一個由特殊的BeanPostProcessor
實(shí)現(xiàn),
能感知@Required
并提供'要求屬性未被設(shè)置時提示'的邏輯。
它很容易配置;只要簡單地把下列bean定義放入你的Spring XML配置中。
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
最后,你還能配置一個RequiredAnnotationBeanPostProcessor
類的實(shí)例來查找
其他Annotation
類型。
如果你有自己的@Required
風(fēng)格的注解這會是件很棒的事。
簡單地把它插入一個RequiredAnnotationBeanPostProcessor
的定義中就可以了。
看個例子,讓我們假設(shè)你(或你的組織/團(tuán)隊(duì))已經(jīng)定義了一個叫做@Mandatory
的屬性。
你能用如下方法讓一個RequiredAnnotationBeanPostProcessor
實(shí)例感知@Mandatory
:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"> <property name="requiredAnnotationType" value="your.company.package.Mandatory"/> </bean>
這是@Mandatory
注解的源代碼。
請確保你的自定義注解類型本身針對目標(biāo)(target)和運(yùn)行時保持策略(runtime retention policy)使用了合適的注解。
package your.company.package; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Mandatory { }