Spring AopのAsppectJコメント構成によるログ管理の実現方法
最近のプロジェクトはログ機能を作ります。Spring Aopの注釈方式で実現します。
ログコメントを作成
操作の方法名、パラメータ、所要時間を記録し、折り返し通知を使用します。
ログコメントの応用
効果
以上のこのSpring AopのAspectJ注釈配置はログ管理の方法を実現します。小編集は皆さんに全部の内容を共有します。参考にしてもらいたいです。どうぞよろしくお願いします。
ログコメントを作成
package com.wyj.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
*
* @author:WangYuanJun
* @date:2016 8 26 8:25:35
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String action() default "";//
}
切面通知類の作成操作の方法名、パラメータ、所要時間を記録し、折り返し通知を使用します。
package com.wyj.aspect;
import java.lang.reflect.Method;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wyj.annotation.SysLog;
import com.wyj.entity.SysLogEntity;
import com.wyj.service.SysLogService;
/**
*
*
*
* @author:WangYuanJun
* @date:2016 8 26 10:28:57
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
/**
*
*/
@Pointcut("@annotation(com.wyj.annotation.SysLog)")
public void pointCut() {}
/**
*
*
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("pointCut()")
public Object aroud(ProceedingJoinPoint joinPoint) throws Throwable {
//
long beginTime = System.currentTimeMillis();
//
Object result = joinPoint.proceed();
// ( )
long time = System.currentTimeMillis() - beginTime;
//
saveSysLog(joinPoint, time);
return result;
}
/**
*
*
* @param joinPoint
* @param time
*/
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLogEntity sysLogEntity = new SysLogEntity();
SysLog sysLog = method.getAnnotation(SysLog.class);
if (sysLog != null) {
//
sysLogEntity.setOperation(sysLog.action());
}
//
String className = joinPoint.getTarget().getClass().getName();
//
String methodName = signature.getName();
sysLogEntity.setMethod(className + "." + methodName + "()");
//
Object[] args = joinPoint.getArgs();
if (args != null && args.length != 0 && args[0] != null) {
sysLogEntity.setParams(args[0].toString());
}
sysLogEntity.setTime(time);
//
sysLogService.save(sysLogEntity);
}
}
スキャンと起動aopコメントログコメントの応用
効果
以上のこのSpring AopのAspectJ注釈配置はログ管理の方法を実現します。小編集は皆さんに全部の内容を共有します。参考にしてもらいたいです。どうぞよろしくお願いします。