场景:想在每一次调用rpc接口的时候,即进入rpc接口的时候进行一个日志的打印
实现:首先定义一下注解类
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLogable {
RequestMethodDTO value();
}
其次对调用注解的地方进行一个处理
@Order(1)
@Aspect
@Component
public class ALogAspect {
/**
* 对方法进行取点
*/
@Pointcut("@within(注解全类名)")
private void printLogMethod() {
/*do nothing*/
}
@Before("printLogMethod()")
public void invoke(JoinPoint joinPoint) {
try {
this.printAccessLog(joinPoint);
} catch (Exception e) {
//打印异常日志
}
}
private void printAccessLog(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
AccessLoggable accessLoggable = methodSignature.getMethod().getAnnotation(AccessLogable.class);
if (null != accessLoggable) {
//打印相关access日志
}
}
}
最后在需要打印日志的地方调用这个注解即可
@Service
Class LogService{
@AccessLogable(value="对象")
public void method(){
//业务逻辑
}
}