當(dāng)我們有很多類需要通知時(shí),顯示的創(chuàng)建每個(gè)代理就會(huì)顯得很笨拙。幸運(yùn)的是,Spring有一個(gè)自動(dòng)代理機(jī)制,它可以讓容器為我們產(chǎn)生代理。Spring有2個(gè)類提供這種服務(wù):BeanNameAutoProxyCreate和DefaultAdvisorAutoProxyCreator.
BeanNameAutoProxyCreate:為匹配一系列名字的Bean自動(dòng)創(chuàng)建代理。它也允許在名字的2端進(jìn)行通配符的匹配。
<?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是一個(gè)Advisor或攔截器,它將應(yīng)用到代理對(duì)象的所有方法上。如果是通知的話,Advisor切入點(diǎn)
會(huì)根據(jù)不同Bean將通知應(yīng)用到不同的地方。
-->
<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>
更強(qiáng)大的自動(dòng)代理創(chuàng)建器是DefaultAdvisorAutoProxyCreator.當(dāng)ApplicationContext讀入所有Bean的配置信息后,DefaultAdvisorAutoProxyCreator將掃描上下文,尋找所有的Advisor.它將這些Advisor應(yīng)用到所有符合Advisor切入點(diǎn)的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>
<!--
一個(gè)Advisor是一個(gè)切入點(diǎn)和一個(gè)通知的結(jié)合體。不用顯示的將Advisor與其他東西結(jié)合,現(xiàn)在只要簡(jiǎn)單的定義他們,然后讓他們自動(dòng)
應(yīng)用到他們匹配的地方。這樣松耦合Bean以及他們的通知就實(shí)現(xiàn)了。你只管寫好你的Bean,寫好你的通知,讓容器來充當(dāng)媒婆。
-->
<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
王永慶 閱讀(259)
評(píng)論(0) 編輯 收藏 所屬分類:
SPRING