如果您要為您的目標物件提供Advice,則您必須為它們建立代理物件,在應用程式規模大時,如果要提供Advice的目標物件很多,則一個一個為它們建立代理物件會是件麻煩的事,為此,Spring為一些情況提供自動代理。
您可以為目標物件取好適當的Bean名稱,例如為某些服務物件取名為xxxService,這麼一來,您可以使用
org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator來為這些
Bean設定自動代理,例如DelegatingIntroductionInterceptor 中就可以改用BeanNameAutoProxyCreator來建立自動代理,只要改一下Bean定義檔就可以了:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="someService" class="onlyfun.caterpillar.Some"/>
<bean id="lockIntroduction" class="onlyfun.caterpillar.LockIntroduction"/> <bean id="lockAdvisor" class="org.springframework.aop.support.DefaultIntroductionAdvisor"> <constructor-arg index="0"> <ref bean="lockIntroduction"/> </constructor-arg> <constructor-arg index="1"> <value>onlyfun.caterpillar.ILockable</value> </constructor-arg> </bean> <bean id="introductionProxyCreator" class="org.springframework.aop.framework. → autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>*Service</value> </list> </property> <property name="interceptorNames"> <value>lockAdvisor</value> </property> </bean> </beans>
執行的結果不變,而這樣的設定,如果您打算讓某個目標物件套用Advice時,就只要將其名稱取名為xxxService就可以了,Spring會自動建立代理物件。
|