首先是几个概念:连接点(Joinpoint)、切点(Pointcut)、增强(Advice)、切面(Aspect)

另外也要使用到注解。

需求:通过注解定义LogEnable。然后程序运行能够识别定义了LogEnable注解的方法记录日志。

1.定义注解

package cn.duanjt.util;

import java.lang.annotation.*;

/**
* 记录日志的注解类
* @author 段江涛
* @date 2018-11-08
*/
@Target(ElementType.METHOD)//表示用于标识方法
@Retention(RetentionPolicy.RUNTIME)//表示运行时保留
public @interface LogEnable {
/**
* 主要是标志日志的描述信息
* @return
*/
String note() default "";
}

2.定义需要监听的类和方法

package cn.duanjt.service;

import org.springframework.stereotype.Service;

import cn.duanjt.Pojo.Student;
import cn.duanjt.util.LogEnable; @Service
public class StudentService {
//定义注解,然后描述当前方法的作用
@LogEnable(note="获取学生信息")
public Student getStudent(int id) {
if (id == 0) {
throw new RuntimeException("编码不能为0");
}
Student stu = new Student();
stu.setId(id);
stu.setName("zhangsan");
stu.setAddr("重庆");
return stu;
} //未定义注解,将不会被监听
public int getId(int id) {
return id + 1;
}
}

3.定义切面,记录日志

package cn.duanjt.util;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogHelper {
// 没有单独定义切点,直接在环绕方法里面处理[包cn.duanjt.service下面的所有类下面的所有方法,同时包含LogEnable注解的将被监听]
@Around("execution(* cn.duanjt.service.*.*(..)) && @annotation(LogEnable)")
public Object around(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
long time = System.currentTimeMillis(); //记录开始时间
String className = point.getTarget().getClass().getName(); // 类名
String method = className + "." + signature.getName(); //方法名
Object[] args = point.getArgs(); // 参数 LogEnable logEnable= signature.getMethod().getAnnotation(LogEnable.class);
String logNote=logEnable.note(); //日志信息
try {
Object result = point.proceed();
System.out.println("方法名:" + method);
System.out.println("参数:" + StringUtils.join(args));
System.out.println("返回值:" + result.toString());
System.out.println("日志功能:" + logNote);
System.out.println("耗时:" + (System.currentTimeMillis() - time) + "毫秒");
System.out.println("-----------------------");
return result;
} catch (Exception e) {
System.out.println("方法名1:" + method);
System.out.println("参数:" + StringUtils.join(args));
System.out.println("日志功能:" + logNote);
System.out.println("异常信息:" + e.getMessage());
System.out.println("耗时:" + (System.currentTimeMillis() - time) + "毫秒");
System.out.println("-----------------------");
return null;
} catch (Throwable e) {
return null;
} }
}

4.在主程序上要加上注解@EnableAspectJAutoProxy。我这里使用的是springboot,如下:

package cn.duanjt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication
@ComponentScan("cn.duanjt")
@EnableAspectJAutoProxy //表示启用AOP
public class ServerDemoApplication { public static void main(String[] args) {
SpringApplication.run(ServerDemoApplication.class, args);
}
}

最后,运行结果如下:

方法名:cn.duanjt.service.StudentService.getStudent
参数:
返回值:Student [id=, name=zhangsan, addr=重庆]
日志功能:获取学生信息
耗时:毫秒
-----------------------

注意:

1. @EnableAspectJAutoProxy用于开启全局的AOP

2. LogHelper类上面的@Aspect和@Component是必须的,前者用于标注是切面,后者用于将对象注入到spring容器

3. 切面表达式@Around("execution(* cn.duanjt.service.*.*(..)) && @annotation(LogEnable)").一定需要execution。详细的可以下去再了解

spring aop通过注解实现日志记录的更多相关文章

  1. 利用Spring AOP自定义注解解决日志和签名校验

    转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...

  2. spring AOP自定义注解 实现日志管理

    今天继续实现AOP,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用Spring AOP 自定义注解形式实现日志管理.废话不多说,直接开始!!! 关于配置我还是的再说一遍. 在appli ...

  3. (转)利用Spring AOP自定义注解解决日志和签名校验

    一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: ...

  4. 运用Spring Aop,一个注解实现日志记录

    运用Spring Aop,一个注解实现日志记录 1. 介绍 我们都知道Spring框架的两大特性分别是 IOC (控制反转)和 AOP (面向切面),这个是每一个Spring学习视频里面一开始都会提到 ...

  5. spring AOP自定义注解方式实现日志管理

    今天继续实现AOP,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用Spring AOP 自定义注解形式实现日志管理.废话不多说,直接开始!!! 关于配置我还是的再说一遍. 在appli ...

  6. Spring Boot 2.X(八):Spring AOP 实现简单的日志切面

    AOP 1.什么是 AOP ? AOP 的全称为 Aspect Oriented Programming,译为面向切面编程,是通过预编译方式和运行期动态代理实现核心业务逻辑之外的横切行为的统一维护的一 ...

  7. spring aop 使用注解方式总结

    spring aop的注解方式:和xml的配置方式略有区别,详细如下: 1.首先还是建立需要的切面类:切面类里面定义好切点配置,以及所有的需要实现的通知方法. /** * */ package com ...

  8. Spring aop+自定义注解统一记录用户行为日志

    写在前面 本文不涉及过多的Spring aop基本概念以及基本用法介绍,以实际场景使用为主. 场景 我们通常有这样一个需求:打印后台接口请求的具体参数,打印接口请求的最终响应结果,以及记录哪个用户在什 ...

  9. Spring AOP使用注解记录用户操作日志

    最后一个方法:核心的日志记录方法 package com.migu.cm.aspect; import com.alibaba.fastjson.JSON; import com.migu.cm.do ...

随机推荐

  1. Java能抵挡住JavaScript的进攻吗?

    JavaScript的进攻 公元2014年,Java 第八代国王终于登上了王位. 第一次早朝,国王坐在高高的宝座上,看着毕恭毕敬的大臣,第一次体会到了皇权的威力. 德高望重的IO大臣颤悠悠地走上前来: ...

  2. Kali系列之Hydra/Medusa mysql密码爆破

    hydra hydra -L /home/chenglee/zidian/user.txt -P /home/chenglee/zidian/wordlist.TXT 192.168.137.133 ...

  3. USB通信基础知识

    1 USB系统组成 主机:提供USB接口和接口管理功能的硬件.软件.固件的复合体.PC机或OTG设备,一个USB系统只能有一个主机 设备:1.集线器HUB:扩展主机接口,设备可以通过其接入主机  2. ...

  4. tp框架中的一些疑点知识-1

    tp默认的编码是utf-8 Runtime中的Cache和Logs都是分模块的,因为在应用app下可以有多个模块,但是 公共模块和Runtime模块只有一个, 所以, Runtime要包含各个模块的内 ...

  5. 【做题】spoj4060 A game with probability——dp

    赛前做题时忽然发现自己概率博弈类dp很弱,心好慌.(获胜概率或最优解期望) 于是就做了这道题,续了特别久. 一开始列dp式子的时候就花了很长时间,首先搞错了两次,然后忘记了根据上一轮dp值直接确定选什 ...

  6. SSM项目开发中的实体定义以及MySQL表格设计

    话不多说,下面表格是项目开发中用到的实体集以及表格Name 实体创建     表格创建 Area 区域 Area 实体 areaId areaName priority createTime last ...

  7. (zhuan) 大牛讲堂 | 算法工程师入门第二期-穆黎森讲增强学习

    大牛讲堂 | 算法工程师入门第二期-穆黎森讲增强学习 2017-07-13 HorizonRobotics

  8. k8s2

    1.主节点与子节点如何沟通,交互 apiServer <==> kublet 2. pod之间如何共享, 使用volumn(数据卷 ) kube-proxy 和 service 配置好网络 ...

  9. cmd中utf-8编码的问题

    有时候我们需要使用cmd显示某个utf-8编码的文本,这时候就需要设置cmd的代码页为65100. 也就是 chcp 65001 这条命令.这样设置可以临时生效. 如何要永久生效,需要在注册表中修改. ...

  10. -第1章 HTMLCSS方法实现下拉菜单

    中英文的自动换行问题 把下面代码中的 javascript 改成 子菜单1 试试, 如果英文的话宽度会自动撑开, 用中文不会, 而直接转行下来. <ul> <li><a ...