设计思路:使用自定义注解加在方法上,这个注解被AOP管理,当方法运行时注解得到信息,注解的信息又可以被AOP得到,在AOP中将注解的信息存放到数据库。
实现如下:
自定义的注解可以自定义属性,基本属性可以是:descript(方法描述),type(crud哪种类型)
/**
* author:lcy
* since 2021/6/19 16:12
* @Target(ElementType.METHOD)表示在方法上生效
* @Retention(RetentionPolicy.RUNTIME)表示运行时生效
* @Documented 说明该注解将包含在javadoc中
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLogAnnotation {
public String descript() default "";
public String type() default "";
}
实现一个切面(aspect),切入点(pointcut)是自定义的注解,通知(advice)类型必须是环绕,必须是环绕的原因是连接点(joincut)的类型是ProceedingJoinPoint而不是JoinPoint。
/**
* author:lcy
* since 2021/6/19 16:16
*/
@Aspect
@Component
public class MyLogAspect {
@Pointcut("@annotation(com.general.aspect.annotation.MyLogAnnotation)")
public void MyAop(){
}
@Around("MyAop()")
public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {
//反射通过target得到该类的全路径
String fullClassPath = joinPoint.getTarget().getClass().getName();
//反射通过signature得到该类的该方法
String runTimeMethod = joinPoint.getSignature().getName();
//aop得到运行结果
Object proceed = joinPoint.proceed();
//通过类名得到该对象
Class<?> aClass = Class.forName(fullClassPath);
//得到该类的所有方法
Method[] methods = aClass.getMethods();
//遍历方法
for (Method method : methods) {
//遍历的方法和该方法名一致则通过getAnnotation拿到该注解
if(method.getName().equals(runTimeMethod)){
MyLogAnnotation annotation = method.getAnnotation(MyLogAnnotation.class);
//方法路径加名称
System.out.println(fullClassPath);
//注解的type类型
System.out.println(annotation.type());
//注解的descript描述
System.out.println(annotation.descript());
//注解的返回数据
System.out.println(proceed);
//在这里可以将信息保存到数据库
//service.save(log)
}
}
return null;
}
}
最后在controller类中需要的方法上加上这个注解就可以了
/**
* @author lcy
* @Description
* @since 2021/6/17 14:34
*/
@Controller
public class GeneralController {
@RequestMapping("/index")
@ResponseBody
@MyLogAnnotation(descript = "什么什么操作",type = "增删改查的哪一个")
public String index(){
Result<Object> result = new Result<>();
result.setResult("成功");
result.setCode(200);
result.setMessage("成功了");
String data = JSON.toJSONString(result);
return data;
}
}
访问localhost:8080/index时运行台出现下面信息