`

Pointcut 介面

阅读更多
来源:http://blog.sina.com.cn/s/blog_3ff3946a01009k95.html
Spring是根据类别名称与方法名称来定义Pointcut(具体的时间),当呼叫的类别与方法名称符合Pointcut的定义时,将Advice(aspect的实例)缝合至应用程式上以提供服务。
Spring的Pointcut是透过实作org.springframework.aop.Pointcut介面来实现,其定义如下:
package org.springframework.aop;
public interface Pointcut {
    ClassFilter getClassFilter();
    MethodMatcher getMethodMatcher();
    Pointcut TRUE = TruePointcut.INSTANCE;
}
Pointcut.TRUE是Pointcut介面的简单实作,它传回的ClassFilter是ClassFilter.TRUE,而传回的MethodMatcher是传回MethodMatcher.TRUE。
ClassFilter介面决定了一个类别是否要应用Advice,其定义如下所示:
package org.springframework.aop;
public interface ClassFilter {
    boolean matches(Class clazz);
    ClassFilter TRUE = TrueClassFilter.INSTANCE;
}
matches()方法中要决定传入的类别是不是符合Pointcut的定义,ClassFilter.TRUE是ClassFilter介面的简单实作,它的matches()方法总是传回true,如果您想要建立的Pointcut只考虑到方法名称,则可以使用这个方法。
而MethodMatcher决定了某个方法是否要应用Advice,其定义如下所示:
package org.springframework.aop;
import java.lang.reflect.Method;
public interface MethodMatcher {
    boolean matches(Method method, Class targetClass);
    boolean isRuntime();
    boolean matches(Method method,
                       Class targetClass, Object[] args);
    MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
}
matches()方法决定了某个类别的某个方法是否符合Pointcut定义,有两个版本,第一个版本使用于静态Pointcut,像是 NameMatchMethodPointcutAdvisor 、 RegExpMethodPointcutAdvisor,第一个方法总是会被执行,如果是静态Pointcut,则isRuntime()会传回 false,此时第二个matches()方法不会被执行,只有在isRuntime()为true时,第二个版本的matches()才会被执行,例如 ControlFlowPointcut 。
MethodMatcher.TRUE是MethodMatcher的简单实作,它的第一个版本的matches()总是传回true, isRuntime()总是传回false,表示静态Pointcut,所以您不可以呼叫第二个版本的matches()方法,否则就会丢出 UnsupportedOperationException 例外。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics