1,AOP简介
面相切面编程(AOP),可以实现例如日志打印、身份认证,权限管理,安全监测。
AOP的实现原理是基于动态代理(Dynamic Proxy)的机制。
本文以操作日志保存为例,主要是介绍通过自定义注解,灵活配置方法是否使用切面,比如身份认证,通过增加注解,可以指定那些方法需要身份认证,实现更灵活使用AOP。
2,创建注解
import java.lang.annotation.*;
/**
* 系统日志注解
*
* @author Aiot_QJ
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
3,日志切面
/**
* 系统日志,切面处理类
* @author Aiot_QJ
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
@Pointcut("@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();
SysLog sysLog = new SysLog();
com.pcidata.common.annotation.SysLog syslog = method.getAnnotation(com.pcidata.common.annotation.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.insert(sysLog);
}
}
4,接口使用
@SysLog("hello world")
@RequestMapping("/hello")
public String hello(@RequestBody String msg){
return "hello world"+msg;
}
总结
通过SpringAOP+注解,可以灵活记录重要接口的日志信息到数据库,方便进行日志分析和统计。
网友评论