在上一篇“SpringBoot 使用@Aspect进行日志管理(基于反射代理模式)”的基础上,添加注解进行日志管理
1、添加日志注解import java.lang.annotation.*;/** * 日志注解 * Created by 陈梓平 on 2017/9/7. */@Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Log { /** 要执行的操作类型比如:add **/ public String operationType() default ""; /** 要执行的模块名称如:Carouse **/ public String modularTypeName() default "";}复制代码
2、修改JournalServiceAspect类
import com.chen.enums.ResultEnum;import com.chen.exception.CustomException;import com.chen.staticInfos.StaticInfo;import com.chen.utils.JournalUtils;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.apache.commons.lang.StringUtils;import org.springframework.transaction.annotation.Transactional;/** * 日志切面 * Created by 陈梓平 on 2017/9/11. */@Component@Aspectpublic class JournalAspect { /**日志输出*/ private static final Logger logger = LoggerFactory.getLogger(JournalAspect.class); /**日志工具类*/ @Autowired private JournalUtils aspectJournalUtils; /**service层切面*/ private final String POINT_CUT = "execution(* com.chen.service..*(..))"; @Pointcut(POINT_CUT) private void pointcut(){} /** * 后置最终通知(目标方法只要执行完了就会执行后置通知方法) * 日志管理 * @param joinPoint */ @After(value = "pointcut()") @Transactional public void doAfterAdvice(JoinPoint joinPoint) throws CustomException, ClassNotFoundException { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); int modulerType = -1; int opreationType = -1; if (methods.length>0){ for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { if (method.getAnnotation(JournalLog.class)!=null){ modulerType = method.getAnnotation(JournalLog.class).modularTypeName(); opreationType = method.getAnnotation(JournalLog.class).operationType(); break; } } } } } //3.添加日志 if (modulerType!=-1&&opreationType!=-1) //TODO 3.1 从请求获取用户id aspectJournalUtils.addJournalInfo(modulerType,opreationType, 10086); }}复制代码
3、修改JournalServiceImpl添加日志注解
/** * Created by 陈梓平 on 2017/9/11. */@Servicepublic class JournalServiceImpl implements JournalService { @Override @JournalLog(operationType = StaticInfo.OPERATIONTYPE_ADD,modularTypeName = StaticInfo.MODEULARTTYPE_FIRST) public Result add() { return ResultUtils.success(ResultEnum.OK); }}复制代码
4、测试结果
1)、接口调用 2)、数据库添加日志数据 附件代码下载: