1.首先编写一个自定义注解
package com.ssm.logAop;
import java.lang.annotation.*;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodLog {
String remark() default "";
String operType() default "0";
}
2.定义切点为自定义注解
@Component
@Aspect
public class LogService {
@Autowired
private LogDao logDao;
public LogService() {
super();
}
/**
* 切点
*/
@Pointcut("@annotation(com.ssm.logAop.MethodLog)")
public void methodCachePointcut() {}
3.切面实现
/**
* 切面
* @throws Exception
*/
@Around("methodCachePointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
String methodRemark = getMthodRemark(point);
String actionName = point.getSignature().getName();
//userId先写死
int userId = 1;
String packages = point.getThis().getClass().getName();
if (packages.indexOf("$$EnhancerByCGLIB$$") > -1) { // 如果是CGLIB动态生成的类
try {
packages = packages.substring(0, packages.indexOf("$$"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Object[] method_param = null;
Object object;
try {
method_param = point.getArgs(); //获取方法参数
for (Object obj : method_param) {
System.out.println("a:"+obj);
}
object = point.proceed(); //这个需要返回,不然出不了切面
} catch (Exception e) {
// 异常处理记录日志..log.error(e);
throw e;
}
ActionLog actionLog = new ActionLog();
actionLog.setUserId(userId);
actionLog.setActionName(actionName);
//在需要记录操作日志的接口上加入@MethodLog(remark="查询**列表")
//当remark的值有以下字段的时候就会获取日志信息存入日志数据库
actionLog.setOperatingcontent(methodRemark);
}
if(methodRemark.indexOf("新增")!=-1 || methodRemark.indexOf("修改")!=-1 || methodRemark.indexOf("删除")!=-1 ||
methodRemark.indexOf("权限变更")!=-1 || methodRemark.indexOf("开门") !=-1) {
actionLog.setOperatingcontent((methodRemark + ":" + method_param[0].toString()).replaceAll(" ", ""));
}
logDao.saveActionLog(actionLog);
return object;
}
4.工具
/**
* 获取方法中的中文备注
*
* @param joinPoint
* @return
* @throws Exception
*/
public static String getMthodRemark(ProceedingJoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] method = targetClass.getMethods();
String methode = "";
for (Method m : method) {
if (m.getName().equals(methodName)) {
Class[] tmpCs = m.getParameterTypes();
if (tmpCs.length == arguments.length) {
MethodLog methodCache = m.getAnnotation(MethodLog.class);
if (methodCache != null) {
methode = methodCache.remark();
}
break;
}
}
}
return methode;
}