重用切点表达式@Pointcut。
一、过多重复的切入点表达式
配置spring aop的时候,我们发现有个细节,就是切入点表达式很多时候是重复使用的:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Before("execution(public * test.calculator.*(..))") public void before(JoinPoint joinPoint) { String methodname = joinPoint.getSignature().getName(); List<Object> list = Arrays.asList(joinPoint.getArgs()); System.out.println("the method is " + methodname + " and args = " + list.toString()); } @After(value = "execution(public int test.calculator.*(..))") public void after(JoinPoint joinPoint) { String methodname = joinPoint.getSignature().getName(); System.out.println("the method " + methodname + " now ends"); } |
同一切入表达式可能出现很多次,每次只有小小的改动或者根本没有改动,但是我们不得不去写它。
这不符合spring的思想,应该考虑如何去重用切入表达式。
二、解决办法
定义一个方法,用于声明切入点表达式,一般情况下该方法中不需要再添入其他的代码。
使用@Pointcut声明切入点表达式。
1 2 3 4 |
@Pointcut(value="execution(public * test.calculator.*(..))") public void declareJoinPointExpression(){ ..... }; |
引用这个注解方法:
1 2 3 4 5 6 7 8 9 10 11 |
@Pointcut(value="execution(public * test.calculator.*(..))") public void declareJoinPointExpression() { ..... }; @Before("declareJoinPointExpression()") public void before(JoinPoint joinPoint) { String methodname = joinPoint.getSignature().getName(); List<Object> list = Arrays.asList(joinPoint.getArgs()); System.out.println("the method is " + methodname + " and args = " + list.toString()); } |
运行结果:
1 2 3 4 5 6 7 8 9 10 |
the method is add and args = [2, 3] validata:[2, 3] the method add now ends the method add has a result = 5 5 the method is div and args = [466, 2] validata:[466, 2] the method div now ends the method div has a result = 233 233 |
正确输出,没有什么不同。
其他切面类要如何获取这个切入表达式呢?
只要加上类名就可以获取了,改成logging.declareJoinPointExpression():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package test; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Aspect @Order(2) public class check { @Before(value="logging.declareJoinPointExpression()") public void check(JoinPoint joinPoint){ System.out.println("validata:" + Arrays.asList(joinPoint.getArgs())); } } |
check中的方法也可以获得logging中的切入表达式。
这样每次配置方法的时候就会很方便,不用每次都写切入表达式。
三、总结
记录一下。