當我們有很多類需要通知時,顯示的創建每個代理就會顯得很笨拙。幸運的是,Spring有一個自動代理機制,它可以讓容器為我們產生代理。Spring有2個類提供這種服務:BeanNameAutoProxyCreate和DefaultAdvisorAutoProxyCreator.
BeanNameAutoProxyCreate:為匹配一系列名字的Bean自動創建代理。它也允許在名字的2端進行通配符的匹配。
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="performanceThresholdInterceptor" class="com.wyq.spring.common.aopinstance.autoproxy.PerformanceThresholdInterceptor">
<constructor-arg>
<value>5000</value>
</constructor-arg>
</bean>
<!--
如果Bean是一個Advisor或攔截器,它將應用到代理對象的所有方法上。如果是通知的話,Advisor切入點
會根據不同Bean將通知應用到不同的地方。
-->
<bean id="performanceThresholdProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<value>performanceThresholdInterceptor</value>
</property>
</bean>
</beans>
更強大的自動代理創建器是DefaultAdvisorAutoProxyCreator.當ApplicationContext讀入所有Bean的配置信息后,DefaultAdvisorAutoProxyCreator將掃描上下文,尋找所有的Advisor.它將這些Advisor應用到所有符合Advisor切入點的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="performanceThresholdInterceptor" class="com.wyq.spring.common.aopinstance.autoproxy.PerformanceThresholdInterceptor">
<constructor-arg>
<value>5000</value>
</constructor-arg>
</bean>
<!--
一個Advisor是一個切入點和一個通知的結合體。不用顯示的將Advisor與其他東西結合,現在只要簡單的定義他們,然后讓他們自動
應用到他們匹配的地方。這樣松耦合Bean以及他們的通知就實現了。你只管寫好你的Bean,寫好你的通知,讓容器來充當媒婆。
-->
<bean id="advisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<bean class="com.wyq.spring.common.aopinstance.autoproxy.PerformanceThresholdInterceptor"></bean>
</property>
<property name="pattern">
<value>.+Service\..+</value>
</property>
</bean>
<bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
</bean>
</beans>
posted on 2009-11-06 16:00
王永慶 閱讀(257)
評論(0) 編輯 收藏 所屬分類:
SPRING