1.首先定义Log注解:
@Target(ElementType.METHOD)//表示只能给类添加该注解
@Retention(RetentionPolicy.RUNTIME)//这个必须要将注解保留在运行时
@Documented//是 java 在生成文档,是否显示注解的开关。
public @interface Log{
/**
* 日志描述
*/
String desc() default "";
/**
* 日志操作类型
*/
OperationType operationType() default OperationType.SYSTEM;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
// public boolean isSaveResponseData() default true;
}
2.之后可以定义操作类型OperationType:
/**
* 操作类型
**/
public enum OperationType {
/**
* 默认系统
*/
SYSTEM("SYSTEM"),
/**
* 登录
*/
LOGIN("LOGIN"),
/**
* 添加
*/
INSERT("INSERT"),
/**
* 删除
*/
DELETE("DELETE"),
/**
* 查询
*/
SELECT("SELECT"),
/**
* 更新
*/
UPDATE("UPDATE");
private String value;
OperationType(String s) {
this.value = s;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
3.声明切面类
/**
* 操作日志切面
**/
@Slf4j //日志输出
@Aspect //把当前类标识为一个切面供容器读取
@Component
public class OptLogAspect {
//这个地方依赖注入业务层接口,可以用@Autowrid或者@Resource注入
/**
* 日志 切面 自定义注解 切到任意方法
*/
@Pointcut("切点表达式")
public void optLog() {
}
@Before("optLog()")
public void doBefore(JoinPoint joinPoint) {
// System.out.println("进入方法前执行...");
}
@Async
@Transactional(rollbackFor = Exception.class)
@AfterReturning(value = "optLog()", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Object result) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
OperationLogSys annotation = signature.getMethod().getAnnotation(OperationLogSys.class);
// 获取切入点所在的方法
Method method = signature.getMethod();
if (annotation != null) {
//操作人(登录名)
String userName = request.getRemoteUser();
//url地址
String requestURL = request.getRequestURL().toString();
//操作方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = method.getName();
methodName = className + "." + methodName;
//描述
String desc = annotation.desc();
//请求方式
String requestWay = request.getMethod();
//操作类型
String operationType = annotation.operationType().getValue();
//你可以将获取到的信息加入实体类中然后,调用日志业务层的插入方法。
//如 logService.insert(log)。log是自定义实体类
}
}
}

被折叠的 条评论
为什么被折叠?



