技术不到位考虑到的比较少。
使用自定义注解对函数进行操作类型设定
//自定义注解
@Target(ElementType.METHOD) //方法注解
@Retention(RetentionPolicy.RUNTIME) //设置生存周期,运行时可见
public @interface LogPointCutAnno {
String operateType() default "";//标记当前操作类型
}
使用环绕通知对日志信息进行获取保存
@Aspect
@Component
public class LogAspect {
@Autowired
private LogService logService;
@Autowired
private HttpServletRequest request;
//@annotation表示标注了某个注解的所有方法。
@Pointcut("@annotation(com.example.AOPLog.LogPointCutAnno)")
public void controllerAspect(){};
/**
* 环绕通知 用于记录日志信息
* @param joinPoint 切点
* @throws InterruptedException
*/
//环绕通知
@Around("controllerAspect()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint){
//前置
System.out.println("preHandle---");
Log log=new Log();
Date time=new Date();//获取操作时间
// System.out.println(admin+"-----------------");
//获取方法签名
MethodSignature signature= (MethodSignature) joinPoint.getSignature();
//获取方法注解
LogPointCutAnno annotation = signature.getMethod().getAnnotation(LogPointCutAnno.class);
//获得操作类型
String operationType= annotation.operateType();
System.out.println(operationType);
//从session获取操作者信息
Admin admin = (Admin) request.getSession().getAttribute("admin");
//获取IP地址
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
System.out.println(admin);
if (admin!=null)
log.setOperator(admin.getAccount());
log.setOperationTime(time);
log.setAction(operationType);
log.setIp(ip);
Object proceed=null;
try {
//后置
proceed = joinPoint.proceed();
System.out.println("AfterHandle---");
//设置操作结果
log.setResult("成功");
} catch (Throwable throwable) {
log.setResult("失败");
throwable.printStackTrace();
}finally {
//最终通知
//保存数据库
logService.insert(log);
}
return proceed;
}
}
xml配置
<!--日志-->
<context:component-scan base-package="com.example.AOPLog"/>
<aop:config proxy-target-class="true"/>
<aop:aspectj-autoproxy/>