1. 程式人生 > >Spring AOP的初步總結(二)

Spring AOP的初步總結(二)

該篇提供了一個小的AOP應用案例:系統日誌

 

@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogService sysLogService;
    
    @Pointcut("@annotation(io.renren.common.annotation.SysLog)")
    public void logPointCut() { 
        
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws
Throwable { long beginTime = System.currentTimeMillis(); //執行方法 Object result = point.proceed(); //執行時長(毫秒) long time = System.currentTimeMillis() - beginTime; //儲存日誌 saveSysLog(point, time); return result; } private void saveSysLog(ProceedingJoinPoint joinPoint, long
time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLogEntity sysLog = new SysLogEntity(); SysLog syslog = method.getAnnotation(SysLog.class); if(syslog != null){ //註解上的描述 sysLog.setOperation(syslog.value()); }
//請求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //請求的引數 Object[] args = joinPoint.getArgs(); try{ String params = new Gson().toJson(args[0]); sysLog.setParams(params); }catch (Exception e){ } //獲取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //設定IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); //使用者名稱 String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername(); sysLog.setUsername(username); sysLog.setTime(time); sysLog.setCreateDate(new Date()); //儲存系統日誌 sysLogService.save(sysLog); } }

此處切點logPointCut是附在註解io.renren.common.annotation.SysLog上的,

下面是註解SysLog:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {

    String value() default "";
}

切面程式碼中sysLogService無疑就是存入資料庫的操作了,寫持久層和建表這裡都不贅述了.

應用的話只要在Controller上所需要的方法貼上註解即可,value給上操作名稱