使用SpringAOP配合自定义注解方式记录日志

1. 自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface UserMedalAnnotation {
    //模块名
    String moduleName() default "";
    //操作内容
    String option() default "";
}

2. 创建一个切面类

import net.newcapec.campus.score.annotation.UserMedalAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class UserMedalLogInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserMedalLogInterceptor.class);

    // 配置织入点
    @Pointcut("execution(public * net.campus.score.service..*.*(..))")
    public void logPointCut() {
    }

    @Around(value = "logPointCut() && @annotation(annotation) &&args(..) ")
    public void interceptorUserMedal(ProceedingJoinPoint pj, UserMedalAnnotation annotation){
        LOGGER.info("===============================记录勋章日志启动===============================");
        LOGGER.info("当前执行模块:" + annotation.moduleName()+",当前执行操作:" + annotation.option());
        //获取方法名
        LOGGER.info("当前执行方法:"+pj.getSignature().getName()+ ",执行的方法参数为:" + Arrays.asList(pj.getArgs()));
        /*执行目标方法*/
        try {
            pj.proceed();
            
            LOGGER.info("方法执行成功");
        }catch (Throwable e){
            LOGGER.error("方法执行失败");
            LOGGER.error("当前执行结果:执行出现异常"+e);
        }
    }
}

@Pointcut 定义切点
1.匹配所有方法: execution(* (…))
2.匹配net.campus.score.service中所有的公有方法 : execution(public * net.campus.score.service.
(…))
3.表示匹配net.campus.score.service包及其子包下的所有方法: execution(* net.campus.score.service….(…))
@Around 定义了此方法为 Around增强处理方法;
可以用来在调用一个具体方法前和调用后来完成一些具体的任务。
@annotation(annotation):参数annotation应该与增强处理方法中的参数名保持一致
proceed() 方法调用了目标方法,并可以获取其返回值;
try…catch 可以捕获到目标方法报错异常

3. 在需要记录日志的方法上添加注解在这里插入图片描述

4. 配置xml文件

<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。
<context:component-scan /> 开启注解扫描


	<!-- 使用CGLib动态代理技术织入增强 -->
    <aop:aspectj-autoproxy expose-proxy="true"/>

	<!-- 开启注解方式 -->
	<context:component-scan base-package="net.newcapec.campus.score"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值