Spirng Aop 實現自定義注解及實現

需求:日志記錄

需要記錄當前用戶訪問的每個接口對應的前端頁面功能信息

聲明一個注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface LogRecord {
    /**
     * 接口功能信息
     */
    String value() default "";
}

定義切面

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.cxbz.chengjiu.common.LogRecord;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class LogRecordAspect {

    // 聲明一個切面
    @Pointcut("execution(public * com.demo.web.*.*(..))")
    public void webLog() {
    }

    // 前置通知
    @Before("webLog()")
    public void before(JoinPoint joinPoint) {
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        //獲取方法上的注解
        LogRecord annotation = method.getAnnotation(LogRecord.class);
        if (annotation != null) {
            // 獲取注解上的參數,在此實現自己的邏輯
            String value = annotation.value();
            System.out.println(value);
        }
    }

    private static final String[] HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR"};

    private String getClientIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }
}

控制層接口添加注解

@RestController
@RequestMapping("/system")
@CrossOrigin
public class LoginController {

    @Autowired
    SystemUserService systemUserService;

    @LogRecord("登陸")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated SystemUser systemUser) {
        return systemUserService.login(systemUser.getUsername(), systemUser.getPassword());
    }

}

控制臺查看注解是否輸出 '登陸'

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容