?
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
Spring有很多自定義的Java 5+注解。
org.springframework.beans.factory.annotation
包
中的@Required
注解能用來(lái)標(biāo)記
屬性,將其標(biāo)示為'需要設(shè)置'(例如,一個(gè)類(lèi)中的被注解的(setter)
方法必須配置一個(gè)用來(lái)依賴(lài)注入的值),否則容器會(huì)在運(yùn)行時(shí)拋出一個(gè)Exception
。
演示這個(gè)注解用法的最好辦法是給出像下面這樣的范例:
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... }
希望上面的類(lèi)定義看起來(lái)還算簡(jiǎn)單。你必須為所有SimpleMovieLister
類(lèi)的BeanDefinitions
提供一個(gè)值。
讓我們看一個(gè)不能通過(guò)驗(yàn)證的XML配置范例。
<bean id="movieLister" class="x.y.SimpleMovieLister">
<!-- whoops, no MovieFinder is set (and this property is @Required
) -->
</bean>
運(yùn)行時(shí)Spring容器會(huì)生成下面的消息(追蹤堆棧的剩下部分被刪除了)。
Exception in thread "main" java.lang.IllegalArgumentException: Property 'movieFinder' is required for bean 'movieLister'.
最后還需要一點(diǎn)(小的)Spring配置來(lái)'開(kāi)啟'這個(gè)行為。
簡(jiǎn)單注解類(lèi)的'setter'屬性不足以實(shí)現(xiàn)這個(gè)行為。
你還需要一個(gè)了解@Required
注解并能適當(dāng)?shù)靥幚硭慕M件。
這個(gè)組件就是RequiredAnnotationBeanPostProcessor
類(lèi)。
這是一個(gè)由特殊的BeanPostProcessor
實(shí)現(xiàn),
能感知@Required
并提供'要求屬性未被設(shè)置時(shí)提示'的邏輯。
它很容易配置;只要簡(jiǎn)單地把下列bean定義放入你的Spring XML配置中。
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
最后,你還能配置一個(gè)RequiredAnnotationBeanPostProcessor
類(lèi)的實(shí)例來(lái)查找
其他Annotation
類(lèi)型。
如果你有自己的@Required
風(fēng)格的注解這會(huì)是件很棒的事。
簡(jiǎn)單地把它插入一個(gè)RequiredAnnotationBeanPostProcessor
的定義中就可以了。
看個(gè)例子,讓我們假設(shè)你(或你的組織/團(tuán)隊(duì))已經(jīng)定義了一個(gè)叫做@Mandatory
的屬性。
你能用如下方法讓一個(gè)RequiredAnnotationBeanPostProcessor
實(shí)例感知@Mandatory
:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"> <property name="requiredAnnotationType" value="your.company.package.Mandatory"/> </bean>
這是@Mandatory
注解的源代碼。
請(qǐng)確保你的自定義注解類(lèi)型本身針對(duì)目標(biāo)(target)和運(yùn)行時(shí)保持策略(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 { }
注解也被用于Spring中的其他地方。那些注解在它們各自的章節(jié)或與它們相關(guān)的章節(jié)中予以說(shuō)明。
第?9.5.6?節(jié) “使用 @Transactional
”
第?6.8.1?節(jié) “在Spring中使用AspectJ進(jìn)行domain object的依賴(lài)注入”
第?6.2?節(jié) “@AspectJ支持”
第?3.11?節(jié) “基于注解(Annotation-based)的配置”
第?3.12?節(jié) “對(duì)受管組件的Classpath掃描”