日誌主題能夠用下面的枚舉類來實現java
package cn.bounter.common.model; /** * 應用日誌主題枚舉類 * @author simon * */ public enum AppLogSubjectEnum { /** 客戶 */ CUSTOMER(1,"客戶"), /** 商品 */ COMMODITY(2,"商品"), /** 訂單 */ ORDER(3,"訂單"); private Integer value; private String name; private AppLogSubjectEnum(int value, String name) { this.value = value; this.name = name; } public Integer getValue() { return value; } public String getName() { return name; } /** * 自定義方法 * 根據枚舉值獲取枚舉字符串內容 * @param value * @return */ public static String stringOf(int value) { for(AppLogSubjectEnum oneEnum : AppLogSubjectEnum.values()) { if(oneEnum.value == value) { return oneEnum.getName(); } } return null; } }
而後讓咱們看下自定義註解spring
package cn.bounter.common.model; import java.lang.annotation.*; /** * 應用日誌註解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AppLog { /** * 日誌主題 * @return */ AppLogSubjectEnum subject(); /** * 日誌內容 * @return */ String content() default ""; }
接下來就是重頭戲基於自定義註解的切面了數據庫
package cn.bounter.common.model; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.time.LocalDateTime; /** * 應用日誌切面 */ @Aspect @Component public class AppLogAspect { @Autowired private ActionLogService actionLogService; @Pointcut("@annotation(cn.bounter.common.model.AppLog)") public void appLogPointCut() { } @AfterReturning("appLogPointCut()") public void addActionLog(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); //獲取註解 AppLog appLog = method.getAnnotation(AppLog.class); if (appLog == null) { return; } //保存數據庫 actionLogService.save( new ActionLog() .setSubject(appLog.subject().getValue()) .setContent(appLog.content()) .setCreateBy(ShiroUtils.getUser()) //獲取當前登陸的用戶 .setCreateTime(LocalDateTime.now()) ); } }
到這裏就差很少,最後讓咱們看下怎麼使用自定義日誌註解app
/** * 新增訂單 * @param order * @return */ @AppLog(subject = AppLogSubjectEnum.ORDER, content = "新增") public void save(Order order) { orderService.save(order); }
看完了以後是否是以爲挺簡單哉!那就趕快本身動手試一試吧!this