一:Aop也能实现过滤拦截操作,那么 Aop和拦截器、过滤器之间的区别:
1.过滤器是作用于url,拦截器也是作用于url,不同的是过滤器拦截所有的请求,而拦截器仅仅拦截方法,Aop是作用于所有方法(包括controller以及service)也就是说Aop的拦截作用范围小,但是他的细致程度是最高的,不像过滤器拦截器仅仅针对一个url进行拦截,没有特定的条件
2.三者执行顺序为:过滤器、拦截器、Aop,越是接近代码才处理逻辑就越是耗费资源,因此有必要并且可以的话,优先级按照顺序来,如果要做细粒度的,比如事务或者是日志拦截这种需要进行细致处理的操作,只能用Aop来进行特定执行。
3.Aop 的@Before 、@After、@Around方法:
@Around是环绕在方法前后(入栈和出栈之间),因为会有个 pjp.proceed(); 方法,此方法代表真正执行了方法,因此可以在之间进行一些事物以及打印日志的需求。具体使用:
方式一:
@Around(value="execution(* *..Service.*(..)) && @annotation(transaction)")
public Object around(ProceedingJoinPoint pjp, Transaction transaction) throws Throwable {
throw new RuntimeException("advice invoked");
//return pjp.proceed();
}
方式二:
@Pointcut("execution(public * com.bestpay.bigdata.aiplus..*Controller.*(..)))")
private void requestCut() {
}
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Before("requestCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
@Around("requestCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {方法三:
@Pointcut("@annotation(com.hmily.tcc.annotation.Tcc)")
切点作用于含有注解的类或者方法上
二:Aop各种方法实例:
ProceedingJoinPoint point
MethodSignature signature = (MethodSignature)point.getSignature(); Method method = signature.getMethod(); Class<?> clazz = point.getTarget().getClass(); Object[] args = point.getArgs(); Hmily hmily = (Hmily)method.getAnnotation(Hmily.class);(方法上有Hmily注解) PatternEnum pattern = hmily.pattern(); hmilyTransaction.setTargetClass(clazz.getName()); hmilyTransaction.setTargetMethod(method.getName());
hmilyTransaction.setPattern(pattern.getCode()); HmilyInvocation confirmInvocation = null; String confirmMethodName = hmily.confirmMethod(); String cancelMethodName = hmily.cancelMethod();