java注解使用
Posted xiafeiyong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java注解使用相关的知识,希望对你有一定的参考价值。
package com.casstime.ec.cloud.cart.infrastructure.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import com.casstime.commons.service.exception.HttpMessageException;
import com.casstime.commons.utils.JsonUtil;
import lombok.extern.log4j.Log4j2;
/**
* 监控配置
*/
@Aspect
@Component
@Log4j2
public class MonitoringActuator {
/**
* 打印含有@Log注解的方法的方法名、入参、出参、执行时长
*/
@Around("@annotation(com.casstime.ec.cloud.cart.infrastructure.aspect.Log)")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
String method = joinPoint.getSignature().getName();
log.info("method:{}, args:{}",
() -> method,
() -> JsonUtil.serializer(joinPoint.getArgs()));
long begin = System.currentTimeMillis();
Object result = joinPoint.proceed();
log.info("method:{}, execute times:{}, result:{}",
() -> method,
() -> System.currentTimeMillis() - begin,
() -> JsonUtil.serializer(result));
return result;
}
/**
* 统一处理接口异常
*/
@AfterThrowing(throwing = "e", pointcut = "execution(public * com.casstime..ec.cloud.cart.interfaces.facade.*.*(..))")
public void handleException(JoinPoint joinPoint, Throwable e) {
if (e instanceof HttpMessageException) {
log.warn("{} error, args:{}", () -> joinPoint.getSignature().getName(), () -> JsonUtil.serializer(joinPoint.getArgs()), () -> e);
}
}
}
package com.casstime.ec.cloud.cart.infrastructure.aspect;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* 在方法上加上该注解, 可以打印入参、出参和方法执行时长
*/
@Retention(RUNTIME)
@Target(METHOD)
public @interface Log {
}
以上是关于java注解使用的主要内容,如果未能解决你的问题,请参考以下文章