StaticMethodMatcherPointcutAdvisor靜態切入點實現切面

通過註解實現接口的日誌記錄,是aop的一大用處。

  • 實現註解
/**
 * @Description Accesslog:
 * @Author LiHaitao
 * @Date 2018/12/21 15:37
 **/


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLogger {
    String description() default "";

}

  • 測試接口

/**
 * Created by Administrator on 2019/7/26.
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;


    @GetMapping(path = "/ok")
    @SystemLogger(description = "查詢學生")    //註解方法處
    public String select() {
        return "ok";
    }
    }
  • aop實現
@Component
public class AopLogService extends StaticMethodMatcherPointcutAdvisor  {

    public AopLogService() {
        this.setAdvice((MethodInterceptor) (methodInvocation) -> {
            Object proceed;
            Log log = null;
            try {
                log = this.createLog(methodInvocation);
                proceed = methodInvocation.proceed();
				//這裏將日誌Log保存或者通過事件機制通知,異步進行處理
            } catch (Throwable a) {
                throw a;
            } 
            return proceed;
        });
    }

    private Log createLog(MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        Object aThis = invocation.getThis();
        SystemLogger methodAnnotation = AopUtil.findMethodAnnotation(aThis.getClass(), method, SystemLogger.class);
        String description = methodAnnotation.description();
        Log log = new Log();
        log.setDescp(description);
        log.setMethod(method.getName());


        Object[] arguments = invocation.getArguments();
        for (Object argument : arguments) {
            if (argument instanceof NewStudentRequest) {
                System.out.println("ok----------------");
            }
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();
        log.setUrl(requestURI);
        return log;

    }


    @Override
    public boolean matches(Method method, Class<?> aClass) {
        SystemLogger annotation = AopUtil.findAnnotation(aClass, method, SystemLogger.class);
        return annotation != null;
    }

matches方法來判斷是否切入,true爲切入,false不切入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章