其他分享
首页 > 其他分享> > 简单日志aop和注解实现

简单日志aop和注解实现

作者:互联网

前沿: 对于日志的aop可以不用自定义注解,但是为了爽一把自定义注解和aop,所以这里做了一个简单的demo

功能说明

在使用了自定义的注解的方法上,如果被调用则,会输出该方法的描述和执行时间

依赖

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

定义注解

/**
 * @author GXM www.guokangjie.cn
 * @date 2019/8/30
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RecordTime {
    String description() default "";
}

实现对自定义注解的aop

主要就是把以前的execution表达式改为注解

@Pointcut(“execution(* com.loongshawn.method.ces….(…))”)

改为

@Pointcut("@annotation(recordTime)")

@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 切点
     * @param recordTime
     */
    @Pointcut("@annotation(recordTime)")
    public void dealTime(RecordTime recordTime) {}


    @Before("dealTime(recordTime)")
    public void doBefore(JoinPoint joinPoint, RecordTime recordTime) {
        // 记录请求到达时间
        log.info("description:{}", recordTime.description());
    }

    @After("dealTime(recordTime)")
    public void doAfter(RecordTime recordTime) {
        log.info("endTime:{}, description:{}", formatDate(new Date()), recordTime.description());
    }


    public String formatDate(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }
}

模拟业务

假如我想知道每次都是什么时间我的fillMoney方法被调用,都是什么时间点冲的钱

@Service
public class OnlineService {

    @RecordTime(description = "fillMoney方法被调用")
    public String fillMoney() {
        return "ok";
    }
}

测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class AopTest {
    @Autowired
    private OnlineService onlineService;
    
    @Test
    public void test(){
        onlineService.fillMoney();
    }
}

结果

控制台就会显示日志了

description:getAllUser方法被调用
endTime:2019-08-30 14:43:39, description:getAllUser方法被调用

标签:RecordTime,description,recordTime,aop,注解,日志,public
来源: https://blog.csdn.net/qq_38263083/article/details/100157248