您的位置:首页 > 编程语言 > Java开发

使用spring aop + 注解完成对业务操作的日志记录

2016-09-19 19:53 591 查看
话不多说直接上代码,不喜勿喷
@After("@annotation(com.你的路径.service.LogAntn)")
public void afterAdvice(JoinPoint joinPoint) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
Object[] args = joinPoint.getArgs();
User user = null;
Map<String, String> paramsMap = null;
for (Object object : args) {
if(object instanceof User){
user = (User)object;
}else if(object instanceof Map){
paramsMap = (Map<String, String>)object;
}
}
LogAntn logAntn = getAntn(joinPoint);
String signature = joinPoint.getSignature().toString(); // 获取目标方法签名
String methodName = signature.substring(signature.lastIndexOf(".") + 1,signature.indexOf("("));
String clazzName = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(clazzName);
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(LogAntn.class)&& method.getName().equals(methodName)) {
opObj opObjType = logAntn.opObjType();
String objVal = opObjType.getValue();//操作对象
opType type = logAntn.type();
String opVal = type.getValue();//操作类型
//添加入库操作
}
}
logger.info("aop log ... this is after Advice......");
}
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAntn {
enum opType{
//		UPDATE,ADD,DELETE,REPORT,SEND,TURNEDDOWN
UPDATE("UPDATE","修改/维护"),
DEL("DEL","删除/撤销"),
ADD("ADD","添加");
private String key;
private String value;
private opType(String key,String value) {
this.key = key;
this.value = value;
}
public String getKey(String key){
return key;
}
public String getValue() {
return value;
}
};
opType type();
enum opObj{//操作的简单描述
REPORT("REPORT","上报审批");

};
opObj opObjType();
}

//获取注解
public static LogAntn getAntn(JoinPoint joinPoint){
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(LogAntn.class);
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring aop