AOP基于注解的切面表达式
1.第一种就是最为普遍的表达式
/**
* 定义controller切入点拦截规则,拦截controller下的所有方法
*/
@Pointcut("execution(public * com.wawa.system.consumer.*ms.*Controller.*(..))")
public void sysLogAspect() {
}
2.第二种是自定义注解的表达式
/**
* 自定义一个注解类。把注解放到你需要切的方法上
*/
@Pointcut("@annotation(com.wawa.system.annotation.NoLogger)")
public void noLogAspect() {
}
3.第三种是条件表达式
@Pointcut("execution(public * com.wawa.system.consumer.*ms.*Controller.*(..))")
public void sysLogAspect() {
}
@Pointcut("@annotation(com.wawa.system.annotation.NoLogger)")
public void noLogAspect() {
}
/**
* 把上面两种表达式作为条件,
* 其意思就是切所有controller并且排除被@NoLogger所注解的方法
*/
@Pointcut("sysLogAspect()&&!noLogAspect()")
public void logAspect() {
}
下面的片段是几个通知的实例
/**
* 拦截控制层的操作日志
* @param joinPoint
* @return
* @throws Throwable
*/
@Before(value = "logAspect()")
public void recordLog(JoinPoint joinPoint) throws Throwable {
SystemLog sysLog = new SystemLog();
// 将当前实体保存到threadLocal
sysLogThreadLocal.set(sysLog);
// 开始时间
HttpServletRequest request = RequestHolder.getHttpServletRequest();
// 获取user-agent信息
String agent = request.getHeader("user-agent");
// 解析agent字符串
UserAgent userAgent = UserAgentUtil.parse(agent);
HashMap<String, Object> map = Maps.newHashMap();
map.put("userAgent", agent);
// 获取浏览器对象
map.put("browser", userAgent.getBrowser().toString());
map.put("engine", userAgent.getEngine().toString());
//获取操作系统对象信息
map.put("os", userAgent.getOs().toString());
// 获取平台信息
map.put("platform", userAgent.getPlatform().toString());
map.put("isMobile", userAgent.isMobile());
LocalDateTime now = LocalDateTime.now();
sysLog.setStartTime(now)
.setClientIp(getIpAddr(request))
.setUserName("system")
.setUserAgent(JSONUtil.toJsonStr(map))
.setCreatedBy("system")
.setUpdatedBy("system")
.setUpdatedTime(now)
.setCreatedTime(now);
LogUtil.getControllerMethodDescription(joinPoint, sysLog);
}
/**
* 返回通知
*
* @param response
* @throws Throwable
*/
@AfterReturning(returning = "response", pointcut = "logAspect()")
public void doAfterReturning(Object response) {
try {
//得到当前线程的log对象
SystemLog sysLog = sysLogThreadLocal.get();
LocalDateTime startTime = sysLog.getStartTime();
long end = System.currentTimeMillis();
long start = startTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
sysLog.setExpendTime(end - start)
.setEndTime(LocalDateTime.now());
// 发布事件
applicationContext.publishEvent(new MyApplicationEvent(sysLog));
//移除当前log实体
sysLogThreadLocal.remove();
} catch (Exception e) {
log.info("返回参数:" + response + " ===》 解析参数错误");
}
}
/**
* 异常通知
*
* @param e
*/
@AfterThrowing(pointcut = "logAspect()", throwing = "e")
public void doAfterThrowable(Throwable e) {
SystemLog sysLog = sysLogThreadLocal.get();
// 异常信息
sysLog.setErrorMsg(LogUtil.getStackTrace(e));
// 发布事件
applicationContext.publishEvent(new MyApplicationEvent(sysLog));
//移除当前log实体
sysLogThreadLocal.remove();
}