【java基础学习】自定义注解+aop实现日志

寄语:今天研究下了注解,发现挺有用的,又想到可以自定义注解实现日志功能,结合大牛们们的代码,梳理了一下:

一、导入依赖

 <!--  springboot快速开始parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>
    
	<dependencies>
 <!--    springWeb包 内含MVC框架,tomcat-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--   spring aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
	</dependencies>

二、项目结构

在这里插入图片描述

三、定义注解

package com.jiali.annotation;

import java.lang.annotation.*;

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

    /*** 模块 */public String title() default "";
    /*** 操作类型* * 此处的 BusinessType 是我自己定义的枚举类* BusinessType.OTHER 代表其他操作*/
    public BusinessType businessType() default BusinessType.OTHER;

    enum BusinessType{
        OTHER,INSERT,UPDATE
    }
    
}

四、定义aop

package com.jiali.aspect;

import com.jiali.annotation.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

//原代码出处:http://www.exyb.cn/news/show-86000.html
//略有改编
@Aspect
@Component
public class LogAspect {
//    slf 的LoggerFactory 获得日志API的对象(输入什么Class对象),用于打印
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    /*** 如果处理请求时出现异常,在抛出异常后执行此处代码*
     *   @param joinPoint 切点
     *   @param controllerLog 注解
     *  @param jsonResult 返回值
     *  */
    //    这里通知类型-后置增强   切点设置为打上了注解对象
    //    注意通知的参数和方法的参数保持一致,先有方法的参数,后有通知的参数,注解只是编译时动态处理(生成代码)
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /*** 如果处理请求时出现异常,在抛出异常后执行此处代码
     * @param joinPoint 切点
     * @param e 异常
     * */
    //    这里通知类型-异常增强
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    /*** 日志处理*/
    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            System.out.println("joinPoint.toString(): "+joinPoint.toString());
            System.out.println("joinPoint.toLongString(): "+joinPoint.toLongString());
            System.out.println("joinPoint.toShortString(): "+joinPoint.toShortString());
            System.out.println("controllerLog.title: "+controllerLog.title());
            System.out.println("controllerLog.businessType: "+controllerLog.businessType());
            System.out.println("jsonResult: "+jsonResult);
            System.out.println("title: "+controllerLog.title());

//            log.debug("我是log.debug:","message...");    //控制台无法显示
//            log.trace("我是log.trace:","message...");   //控制台无法显示
//            log.error("我是log.error:","message...");    //可打印
//            log.info("我是log.info:","message...");       //可打印
//            log.warn("我是log.warn:","message...");       //可打印
        } catch (Exception exp) {
            // 记录本地异常日志log.error("**** 出现异常 ****");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }
}

五、控制层和启动类

package com.jiali.controller;

import com.jiali.annotation.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HiController {
    private static final Logger log = LoggerFactory.getLogger(HiController.class);

    @GetMapping(value = "/hi")
    @Log(title = "你好",businessType = Log.BusinessType.OTHER)
    public String hi(){
//        log.info("这里是你好...");
        log.info("这里是名字:"+log.getName());
        return "hi....";
    }

}

六、执行结果

在这里插入图片描述
引用:
aop层代码出处(已做略微改动):
Spring Boot 使用自定义注解实现操作日志的记录

本文项目代码下载地址(使用git工具克隆,或点开链接下载zip):
https://gitee.com/jk4086448/annotation-for-log.git

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值