我有一个返回对象的方法。我想使用 spring AOP 在我的日志中打印该对象的值。我怎样才能做到这一点?
请帮忙!
将 @AfterReturning 与 returnValue 参数一起使用。
然后您可以询问返回的对象 这是一个示例,我对所有内容都执行此操作,但在存储库中获取方法
@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);
}
}
在我们的例子中,大多数时候我们返回 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.");
}
}
在这上面花了很多时间,所以放在这里...
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));
}
}