Spring AOP中的pointcut:
PointCuts用于定義所需要“攔截”的class及其method。分為靜態、動態兩種pointcut。其中靜態pointcuts僅和class name, method name相關,可以在配置文件中通過正則表達式進行部署,因此它們都可以在運行前進行確認。而動態pointcuts則需要考慮到方法的參數,在運行時動態的確認pointcuts。一般來說,都是根據method和class的名字來進行。其涉及到的接口如下定義:
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
}
public interface ClassFilter {
boolean matches(Class clazz);
}
public interface MethodMatcher {
boolean matches(Method m, Class targetClass);
boolean isRuntime();
boolean matches(Method m, Class targetClass, Object[] args);
}
兩種靜態pointcut的實現:
NameMatchMethodPointcut:只能對方法名進行判別。
RegexpMethodPointcut:可以對類名、方法名使用正則表達式判別。
<beans>
<bean id="maidServiceTarget"
class="com.springinaction.chapter03.cleaning.MaidService"/>
<bean id="queryInterceptor" class="com.springinaction.chapter03.cleaning.QueryInterceptor"/>
<bean id="queryPointcutAdvisor"
class="org.springframework.aop.support.RegExpPointcutAdvisor">
<property name="pattern">
<value>.*get.+By.+</value>
</property>
<property name="advice">
<ref bean="queryInterceptor"/>
</property>
</bean>
<bean id="maidService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.springinaction.chapter03.cleaning.MaidService</value>
</property>
<property name="interceptorNames">
<list>
<value>queryPointcutAdvisor</value>
</list>
</property>
<property name="target">
<value ref="maidServiceTarget">
</property>
</bean>
</beans>
一種動態pointcut的實現:
ControlFlowPointcut:根據當前運行棧的情況,決定當前的advice是否需要被觸發。因為它完全基于運行時棧的情況做決策,所以運行速度肯定會變慢。
<beans>
<bean id="myServiceTarget" class="MyServiceImpl"/>
<bean id="servletInterceptor" class="MyServletInterceptor"/>
<bean id="servletPointcut" class="org.springframework.aop.support.ControlFlowPointcut">
<constructor-arg>
<value>javax.servlet.http.HttpServlet</value>
</constructor-arg>
</bean>
<bean id="servletAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice">
<ref bean="servletInterceptor"/>
</property>
<property name="pointcut">
<ref bean="servletPointcut"/>
</property>
</bean>
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>MyService</value>
</property>
<property name="interceptorNames">
<list>
<value>servletAdvisor</value>
</list>
</property>
<property name="target">
<value ref="myServiceTarget">
</property>
</bean>
</beans>