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());
    }

}

控制台查看注解是否输出 ‘登陆’

posted @ 2022-01-20 23:22  暮雨寒冬  阅读(45)  评论(0编辑  收藏  举报