aop

Log

package com.fh.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface/*注解类*/ Log {
    //模块名称
    String name();
}

Aspect

package com.fh.aop;

import com.fh.annotation.Log;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.*;

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

@Component
@Aspect
public class SysAspect {
    //@annotation:当执行的方法上拥有指定的注解时生效
    @Pointcut("@annotation(com.fh.annotation.Log)")
    public void pointcut() {

    }

    @SneakyThrows
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (method != null) {
            Log logAnnotation = method.getAnnotation(Log.class);
            System.out.println(logAnnotation.name());
        }
        System.out.println("方法名=" + method.getName());

        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                        .getRequest();
        System.out.println("ip=" + request.getRemoteAddr());
        System.out.println("uri=" + request.getRequestURI());
        System.out.println("请求方式=" + request.getMethod());
        System.out.println("请求时间=" + new Date());
        return joinPoint.proceed();
    }
}

controller

package com.fh.controller;

import com.fh.annotation.Log;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Log(name = "根据id获取用户")
    @RequestMapping("/user/{id}")
    public String hello(@PathVariable int id) {
        return "user" + id;
    }

}

测试结果

根据id获取用户
方法名=hello
ip=127.0.0.1
uri=/user/132
请求方式=GET
请求时间=Tue Aug 20 11:09:12 CST 2024
posted @ 2024-08-20 11:14  干饭达人GoodLucy  阅读(4)  评论(0编辑  收藏  举报