自定义日志注解

1.编写自定义注解

AOP依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
    String value() default "";
}
2.编写切面
@Aspect
@Component
public class LogAspect {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.example.demo.common.Action)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            Action action = method.getAnnotation(Action.class);
            logger.info(action.value());

            long start = System.currentTimeMillis();
            Object obj = joinPoint.proceed();
            logger.info("timeCost:" + (System.currentTimeMillis() - start));
            return obj;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
3.验证
@SpringBootApplication
@RestController
@RequestMapping("/aop");
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Action("这是一个测试")
    @RequestMapping("/test")
    public String test(){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

这里写图片描述


版权声明:本文为VitaminZH原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。