注解方法實現過程中可以采用如下獲取方式:—以下為例
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
1.定義兩個方法注解,分別標記要處理的http接口及Webservice接口:
http接口注解
1
2
3
4
5
|
@Retention
(RetentionPolicy.RUNTIME)
@Target
({ ElementType.TYPE, ElementType.METHOD })
public
@interface
AnnotationForIntfMark {
String value();
}
|
WebService接口注解
1
2
3
4
5
|
@Retention
(RetentionPolicy.RUNTIME)
@Target
({ ElementType.TYPE, ElementType.METHOD })
public
@interface
AnnotationForWsMark {
String value();
}
|
2.定義Spring AOP切入點,兩種接口注解切入點,注意 中間用||,網上也有說明使用or,試過之后發現or后面的切入點無效
1
2
3
|
@Pointcut
(
"@annotation(ms.platform.base.interfaces.AnnotationForIntfMark) || @annotation(ms.platform.base.interfaces.AnnotationForWsMark)"
)
public
void
pointcut() {
}
|
3.環繞式加入切入點
1
2
3
4
5
6
7
8
9
10
|
@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(
"\n"
);
Object retVal = joinPoint.proceed();
String respParam = postHandle(retVal);
sb.append(
"Output Param:【"
).append(respParam).append(
"】"
).append(
"\n"
);
MSLog.error(sb.toString());
}
|
4.preHandle(joinPoint)獲取接口入參,postHandle(retVal)獲取接口出參
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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();
}
|
1
2
3
|
private
String postHandle(Object retVal) {
return
JsonUtil.bean2json(retVal);
}
|
1
|
|
5.切面類定義,注意需要添加@Component,否則將掃描不到切面類
1
2
3
4
5
|
@Aspect
@Component
public
class
WebRequestAroundAdvice {
}
|