切面编程用来写操作日志真好用啊!
这里我只写例子来记录,想深入了解的去看别的文章哈!
/**
* 定义一个切面容器类
*
*/
@Aspect
@Component
public class XXXAspect {
// 可以表名整个类的方法都走此切面
// 这里定义OpLog注解来指定方法走此切面
@Pointcut("@annotation(com.xxx.OpLog)")
public void logPointCut() {
}
//环绕切面
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
// 方法执行前的操作
xxx(point);
// 执行方法
Object result = point.proceed();
// 方法执行后的操作
yyy();
return result;
}
private void xxx(ProceedingJoinPoint point) throws JsonProcessingException {
// 获取方法
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
// 获取类
Class class = point.getTarget().getClass();
// 获取方法参数
point.getArgs();
// 获取方法的注解
method.getAnnotation(OpLog.class);
// 获取类的注解
class.getAnnotation(xxx.class);
// do something...
}
private void yyy(){
// do something...
}
}
/**
* 自定义注解
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OpLog {
String operateType();
}
/**
*
*具体的实现类
*/
@Service
private class xxxServiceImpl implements xxxService{
//**********
@Override
@OpLog(operateType = "新增") // 这里建议写个注解,不要写 新增 二字
@Transactional(rollbackFor = Exception.class)
public void save(Object entity) {
// do something...
}
//**********
}