我有一个返回对象的方法。我想使用spring AOP在我的日志中打印该对象的值。我怎样才能做到这一点?
请帮忙!
答案 0 :(得分:10)
将@AfterReturning与returnValue参数一起使用。
然后您可以对返回的对象进行interogate 这是一个示例,我在所有内容上执行此操作,但在存储库中获取方法
@AfterReturning(value = "@target(org.springframework.stereotype.Repository) && !execution(* get*(..))", returning = "returnValue")
public void loggingRepositoryMethods(JoinPoint joinPoint, Object returnValue) {
String classMethod = this.getClassMethod(joinPoint);
if(returnValue !=null)
{
//test type of object get properties (could use reflection)
log it out
}
else
{
//do logging here probably passing in (joinPoint, classMethod);
}
}
答案 1 :(得分:5)
在我们的例子中,大多数时候我们返回spring modal的实体类,所以我们用所需的最小信息覆盖所有实体类的toString方法并打印如下
@AfterReturning(pointcut = "within(@org.springframework.stereotype.Service *)", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info(" ###### Returning for class : {} ; Method : {} ", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
if (result != null) {
logger.info(" ###### with value : {}", result.toString());
} else{
logger.info(" ###### with null as return value.");
}
}
答案 2 :(得分:1)
只需记录joinPoint.proceed()方法的返回值......
就可以了答案 3 :(得分:0)
花了一段时间,所以放在这里...
package com.mycomp.poc.JcachePoc.config;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Aspect
@Component
@Slf4j
public class LoggingAspectConfig {
private static LoggingAspectConfig loggingAspectConfig;
@Bean
public LoggingAspectConfig createBean() {
if(loggingAspectConfig==null)
return new LoggingAspectConfig();
else
return loggingAspectConfig;
}
private LoggingAspectConfig () {
}
@Before("execution(* com.mycom.poc.JcachePoc.service*.*.*(..)) && @annotation(Log)")
public void logBefore(JoinPoint joinPoint) {
if(log.isDebugEnabled()) {
Object[] args= joinPoint.getArgs();
Map<String, String> typeValue= new HashMap<>();
for(Object obj: args) {
if(obj!=null) {
typeValue.put(obj.getClass().getName(), obj.toString());
}
}
//log.debug("calling Method:"+joinPoint.getSignature().getDeclaringTypeName()+", "+joinPoint.getSignature().getName()+", Parameter:-> "+ typeValue);
}
}
@AfterReturning(pointcut = "execution(* com.mycom.poc.JcachePoc.service*.*.*(..)) && @annotation(Log)", returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
if (log.isDebugEnabled() && result!=null) {
log.debug("Method returned:" +
joinPoint.getSignature().getName() + ", Result: " + result.getClass().getName()+" -->"+result);
}
//log.info(gson.toJson(result));
}
}