zoukankan      html  css  js  c++  java
  • Spring AOP 自定义注解获取http接口及WebService接口入参和出参

    1.定义两个方法注解,分别标记要处理的http接口及Webservice接口:

    http接口注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    public @interface AnnotationForIntfMark {
    	String value();
    }
    

    WebService接口注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    public @interface AnnotationForWsMark {
    	String value();
    }
    

    2.定义Spring AOP切入点,两种接口注解切入点,注意 中间用||,网上也有说明使用or,试过之后发现or后面的切入点无效

    @Pointcut("@annotation(ms.platform.base.interfaces.AnnotationForIntfMark) || @annotation(ms.platform.base.interfaces.AnnotationForWsMark)")
    	public void pointcut() {
    	}
    

    3.环绕式加入切入点

    @Around("pointcut()")
    	public void handle(ProceedingJoinPoint joinPoint) throws Throwable {
    		StringBuffer sb = new StringBuffer();
    		String reqParam = preHandle(joinPoint);
    		sb.append("Input Param:【").append(reqParam).append("】").append("
    ");
    		Object retVal = joinPoint.proceed();
    		String respParam = postHandle(retVal);
    		sb.append("Output Param:【").append(respParam).append("】").append("
    ");
    		MSLog.error(sb.toString());
    	}
    

    4.preHandle(joinPoint)获取接口入参,postHandle(retVal)获取接口出参

    private String preHandle(ProceedingJoinPoint joinPoint) {
    		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
    				.getRequest();
    		Signature signature = joinPoint.getSignature();
    		MethodSignature methodSignature = (MethodSignature) signature;
    		Method targetMethod = methodSignature.getMethod();
    		Annotation[] annotations = targetMethod.getAnnotations();
    		boolean isIntf = false;
    		StringBuffer sb = new StringBuffer();
    		for (int i = 0; i < annotations.length; i++) {
    			if (annotations[i].annotationType().equals(AnnotationForIntfMark.class)) {
    				sb.append(request.getAttribute("jsonContent"));
    				isIntf = true;
    				break;
    			}
    		}
    		if (!isIntf) {
    			Object[] args = joinPoint.getArgs();
    			for (int j = 0; j < args.length; j++) {
    				sb.append(JsonUtil.bean2json(args[j]));
    			}
    		}
    		return sb.toString();
    	}
    
    private String postHandle(Object retVal) {
    		return JsonUtil.bean2json(retVal);
    	}
    
    
    

    5.切面类定义,注意需要添加@Component,否则将扫描不到切面类

    @Aspect
    @Component
    public class WebRequestAroundAdvice {
    
    }
    
  • 相关阅读:
    n个元素进栈,有几种出栈方式
    The following IP can be used to access Google website
    一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的 相对顺序 比如: input: 1,7,-5,9,-12,15 ans: -5,-12,1,7,9,15 要求时间复杂度O(N),空间O(1) 。
    当今世界最受人们重视的十大经典算法
    指针
    变量作用域和生存期
    一篇文章搞清spark内存管理
    Spark的Shuffle是怎么回事
    一篇文章搞清spark任务如何执行
    scala这写的都是啥?一篇文章搞清柯里化
  • 原文地址:https://www.cnblogs.com/zcs201093189/p/spring_aop.html
Copyright © 2011-2022 走看看