ノート/カスタム注釈+ AOPのログデカップリング

1:@RestControllerコメント+ AOP

 

@ SLF4J 
@Aspect 
@Component 
パブリック クラスControllerLogAspect { 

    @Pointcut( "@within(org.springframework.web.bind.annotation.RestController)" 公共 ボイドfuncLog(){ 
    } 

    @Around( "funcLog()" パブリックオブジェクトfuncLogProcess (ProceedingJoinPoint点)がスローされたThrowable { 
        HttpServletRequestのリクエスト = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())のGetRequest(); 
        文字列のURL = 。request.getRequestURL()のtoString(); 

        オブジェクトobjResp =point.proceed(); 

        log.info( "URL:{} --request:{} --response:{}"、URL、point.getArgs()長さ> 0 JsonUtil.of(point.getArgs()[0])? " " 、JsonUtil.of(objResp))。
        返すobjRespを。
    } 
}

 

 

 

2:カスタム注釈@ MethodLog + AOP

@Documented 
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
パブリック @のインタフェースMethodLog {
     ブール応答()デフォルト 
}
@ SLF4J 
@Aspect 
@Component 
パブリック クラスMethodLogAspect { 

    @Pointcut( "@Annotation(com.example.demo.common.annotation.MethodLog)" 公共 ボイドfuncLog(){ 
    } 

    @Around( "funcLog()" パブリックオブジェクトfuncLogProcess (ProceedingJoinPoint点)がスローされたThrowable { 
        MethodSignature署名 = (MethodSignature)point.getSignature(); 
        方法メソッド = signature.getMethod()。

        オブジェクトobjResp = point.proceed()。

        methodLog methodLog= AnnotationUtils.findAnnotation(方法、MethodLog。クラス)。
        もし(!methodLog = NULL && methodLog.response()){ 
            log.info( "方法:{} --args:{} --resp:{}"、method.getName()、point.getArgs()長さ?> 0 JsonUtil.of(point.getArgs()[0]): "" 、JsonUtil.of(objResp))。
        } { 
            log.info( "方法:{} --args:{}"、method.getName()、point.getArgs()長さ> 0 JsonUtil.of(point.getArgs()[0])?: "" ); 
        } 
        戻りobjResp。
    } 
}

 

おすすめ

転載: www.cnblogs.com/xiao-xin-xin/p/11128192.html