记录一下工作里用到的aop

一个非常简单的需求功能,需要记录后台操作人员的相关日志信息

一条条写入逻辑代码里肯定是不现实的,这时候可以用到aop来解决

  1.  切面类

@Component:标识该类是一个bean,加载到spring容器,

@Aspect:作用是把当前类标识为一个切面供容器读取,

@Pointcut:作用是定义切入点(pointcut)。切入点是在应用程序中选择特定方法进行增强(如添加日志、事务管理等)的规则。
@Around:可以用来在调用一个具体方法前和调用后来完成一些具体的任务

 

@Component
@Aspect
@Slf4j
public class SysLogAspect {
    @Autowired
    UserWsdlService userWsdlService;

    @Autowired
    ISysLogsService logsService;

    /**
     * 声明式切入表达式
     */
    @Pointcut("@annotation(com.eagle.manage.annotation.SysLog)")
    public void controllerAspect() {}

    @Around("controllerAspect()")
    public Object aroundMethod1(ProceedingJoinPoint pjp){
        HttpServletRequest request = WsAnnotationUtils.getRequest();
        Class<?> target = pjp.getTarget().getClass();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Object rest = null;
        SysLog systemLog;
        SysLogs entity = new SysLogs();
        try {
//其他相关逻辑
            logsService.save(entity);
        }catch (Throwable e) {
            e.printStackTrace();
            log.info(e.getClass().getName());
        }
        return rest;
    }
}
2.注解代码:

  3.注解源码:

@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SysLog {
/**
 * 标题
 */
    String title() default "";
/**
 * 操作类型
 */
    LogTypeEnum type();
/**
 * 异常信息
 */
    String exception() default "normal";
/**
 * 是否持久化保存
 */
    boolean persisted() default true;
}

 

 

 

 

posted @ 2024-06-20 15:39  SweetCukes  阅读(17)  评论(0编辑  收藏  举报