首先,需要两行配置
<!--自定义切面所在包-->
<context:component-scan base-package="cn.com.reformer.aop"/>
<!--识别切面,开启CGLIB动态代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
(一)自定义注解方法
1.自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Log {
LogType type() default LogType.SPACE;
}
2.LogType枚举类型
public enum LogType {
SPACE(""),
INSERT("增加"),
DELETE("删除"),
UPDATE("修改"),
QUERY("查询");
private String description;
private LogType( String string) {
description=string;
}
public String GetDescription()
{
return description;
}
}
3.自定义切面
// @Pointcut("@annotation(cn.com.reformer.annotation.Log) && @annotation(log)")
// public void serviceAspect(Log log) {
// }
// @AfterThrowing(pointcut = "serviceAspect(log)", throwing = "e")
@AfterThrowing(value = "@annotation(cn.com.reformer.annotation.Log) && @annotation(log)", throwing = "e")
private void doAfterThrow(JoinPoint joinPoint, Log log, Throwable e){
//读取中的用户
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Admin user = (Admin) request.getAttribute(Constants.CURRENT_ADMIN);
ExceptionLog exceptionLog = new ExceptionLog();
exceptionLog.setUserId(user.getId());
exceptionLog.setIpAddr(getIP(request));
exceptionLog.setOccurTime(new Date());
Object[] os = joinPoint.getArgs();
//获取类名
String className = joinPoint.getTarget().getClass().getSimpleName();
//获取方法名
String methodName = joinPoint.getSignature().getName();
String location = className + "." + methodName + ":";
exceptionLog.setExceptionCode(location+e.getClass().getSimpleName()+e.getMessage());
exceptionLog.setOperation(log.type().GetDescription());
//写入数据库
exceptionLogService.add(exceptionLog);
return;
}
//获取请求IP
public String getIP(HttpServletRequest request) {
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.getRemoteAddr();
}
return ip;
}
(二)不用注解指定捕获异常的方法,确定需要捕获异常的包
controller目录任意下一级目录的任意类的所有方法
(..)表示任意参数
@AfterThrowing(value = "execution(* cn.com.reformer.web.controller.*.*.*(..))", throwing = "e")
private void doAfterThrow(JoinPoint joinPoint, Throwable e) {
}
其他同上