《Spring Recipes》第三章笔记5:Pointcut Expressions
Method Signature Patterns
最常用的匹配模式,根据方法的签名进行匹配。
格式:返回类型模式,方法名模式,方法参数模式还是必须的,其余的模式都可以省略不写。
execution(modifiers-pattern? return-type-pattern declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?)
如:execution(public int com.apress.springrecipes.calculator.ArithmeticCalculator.*(..))
在表达式中,使用*匹配任意字符,使用..匹配任意个参数或者任意包。
Type Signature Patterns
匹配在特定类型中定义的方法。
1、within(com.apress.springrecipes.calculator.*)匹配所有com.apress.springrecipes.calculator包中的类的方法。
2、within(com.apress.springrecipes.calculator.ArithmeticCalculatorImpl)匹配所有com.apress.springrecipes.calculator.ArithmeticCalculatorImpl中方法,如果方面和切入点在同一个包中,可以省略包名within(ArithmeticCalculatorImpl)。
3、可以在接口名后添加+来匹配所有实现了该接口的类:within(ArithmeticCalculator+)。
4、可以定义一个注解,将此注解添加到类上,然后使用within匹配这个注解:
@LoggingRequired
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
...
}
使用表达式:@within(com.apress.springrecipes.calculator.LoggingRequired)匹配ArithmeticCalculatorImpl中所有方法。
Bean Name Patterns
从Spring2.5开始,容器直接使用配置文件中定义的bean的name进行匹配。
注意:值适用于XML配置文件的AOP,不能在AspectJ注解中使用。
bean(*Calculator)
匹配所有已经Calculator结尾的bean。
Combining Pointcut Expressions
AspectJ支持通过&& (and),|| (or),和 ! (not)对表达式进行组合。
@Aspect
public class CalculatorPointcuts {
@Pointcut("within(ArithmeticCalculator+)")
public void arithmeticOperation() {}
@Pointcut("within(UnitCalculator+)")
public void unitOperation() {}
@Pointcut("arithmeticOperation() || unitOperation()")
public void loggingOperation() {}
}
Declaring Pointcut Parameters
可以通过Pointcut Expressions表达式中的特殊符号获取Pointcut 对象的类型和方法参数。
使用target()获取target object,使用args()获取方法参数。
@Aspect
public class CalculatorPointcuts {
... ...
@Pointcut("execution(* *.*(..)) && target(target) && args(a,b)")
public void parameterPointcut(Object target, double a, double b) {}
}
@Aspect
public class CalculatorLoggingAspect {
... ...
@Before("CalculatorPointcuts.parameterPointcut(target, a, b)")
public void logParameter(Object target, double a, double b) {
log.info("Target class : " + target.getClass().getName());
log.info("Arguments : " + a + ", " + b);
}
}