Consider the following snippet of code which outlines a join point that intercepts all Spring beans annotated with @PermitAll:
the idea being that this interceptor should log arguments, return value and the method name for the calls it intercepts. For this output to be usable we need to a way to distinguish between void methods and methods that simply return null (a void method also has a return value in reflection). A simple way to accomplish this is to use a regular expression which discovers void methods based on their signature:
@Around("@annotation(javax.annotation.security.PermitAll)")
public Object securityAdvice(ProceedingJoinPoint jp)
throws Throwable {
Object[] args = jp.getArgs();
Signature signature = jp.getSignature();
String methodName = signature.getName();
// log method name, arguments and return value
// :
}
this however seams a bit to much magic, a better way is to retrieve the java.lang.reflect.Method object and use its return type evaluator:
String voidMatch = String.format(".* void .*(%s).*", methodName);
boolean voidMethod = signature.toLongString().matches(voidMatch);
The full interceptor, is shown below:
Type returnType = signature.getMethod().getGenericReturnType();
boolean voidMethod = returnType.equals(void.class);
@Around("@annotation(javax.annotation.security.PermitAll)")
public Object securityAdvice(ProceedingJoinPoint jp) throws Throwable {
// before execution
Object[] args = jp.getArgs();
MethodSignature signature = (MethodSignature) jp.getSignature();
String methodName = signature.getName();
// determine if this is a void method
Type returnType = signature.getMethod().getGenericReturnType();
final boolean voidMethod = returnType.equals(void.class);
// continue execution
Object res = null;
try {
res = jp.proceed();
return res;
} finally {
// get return value
String returnValue = (res == null) ? "" : res.toString();
if (voidMethod)
returnValue = "";
// log method signature, arguments and return value
final String msg = String.format(
"around method: %s with args: '%s' which returned: %s",
methodName, args.toString(), returnValue);
logger.info(msg);
}
}
remember to register this advice with Spring (or even better use AspectJ auto discovering).





By: Don Delillo