springAOP实例

===main=

package javacommon.util;
//使用 lang下的 反射 reflect 下的方法包
import java.lang.reflect.Method;
//use apache below 's logging Log
import org.apache.commons.logging.Log;
//use logfactory
import org.apache.commons.logging.LogFactory;
//use aspectj proceedingJoinPoint 断点包
import org.aspectj.lang.ProceedingJoinPoint;
//use annotation around 、Aspect、 pointCut
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
//use springframework componet
import org.springframework.stereotype.Component;

import com.bill.system.model.SysUser;

//use 标记是 切片类 且用到组件 。 ok !
@Aspect
@Component
public class MethodLogAspectJ {
protected Log logger = LogFactory.getLog(getClass());

  @Pointcut("@annotation(javacommon.util.MethodLog)")
public void methodCachePointcut() {
}


//@Pointcut("execution (* com.bill.system.dao..*.insert*(..))")

// @Pointcut(“execution (* com.bill.system.dao..(…))”)
public void pointcut(){}

//@AfterThrowing(pointcut="pointcut()",throwing="ex")
//@Around("pointcut()")
@Around("methodCachePointcut()")
public Object methodCacheHold(ProceedingJoinPoint joinPoint)
		throws Throwable {
	System.out.println("aop start ");
	String methodRemark = getMthodRemark(joinPoint);
	
	int keyMarkIndex = this.getPraseMarkKeyIndex(methodRemark);
	String keyType = this.getPraseMarkKeyType(methodRemark);
	Object result = null;
	try {
		// 记录操作日志...谁..在什么时间..做了什么事情..
		Object obj[] = joinPoint.getArgs();
		String keyValue = "";
		//for(int i=0;i<obj.length;i++){
			//System.out.print("@@"+obj[keyMarkIndex]+"\n\r");
			if(StringUtil.isNotEmpty(keyType)&&keyType.equalsIgnoreCase("object")){
				 keyValue = this.getObjectValue(methodRemark,obj,keyMarkIndex);
			}
			else if(StringUtil.isNotEmpty(keyType)&&keyType.equalsIgnoreCase("string")){
				 keyValue = this.getStringValue(methodRemark,obj,keyMarkIndex);
			}
			else{
				//如果是无参数的方法,关键字为空;
				keyValue ="";
				//如果是有参数的type=string的方法,关键字为:
				//??
			}
			
		//}
		//如果无参数  logUtil 第二个参数 为空
		

		result = joinPoint.proceed();
		LogUtil.insertLog("", methodRemark.split(",")[0]+",用户ID:"+keyValue);
	} catch (Exception e) {
		// 异常处理记录日志..log.error(e);
		logger .error("["+SessionUtil.getLoginBranch()+"---"+SessionUtil.getLoginUserAcc()+"---"+DateUtil.getCurrentDate1()+"]"+methodRemark+"失败!", e);
		//throw e;
	}

	System.out.print(methodRemark);
	System.out.println("aop end ");
	return result;
}

private String getObjectValue(String methodRemark, Object[] obj,int keyMarkIndex) {
    String keyValue= methodRemark.split(",")[3];
    String mark =  obj[keyMarkIndex].toString();
    String resValue =mark.substring(mark.indexOf(keyValue+"="),mark.length());
    String res = resValue.split("\r\n")[0];
	return res;
}

private String getStringValue(String methodRemark, Object[] obj,int keyMarkIndex) {
    String keyValue= methodRemark.split(",")[3];
    String mark =  obj[keyMarkIndex].toString();
    String res = keyValue + mark;
	return res;
}
private String getPraseMarkKeyType(String methodRemark) {
	String type = "";
	Object args[]= methodRemark.split(",");
	if(args.length>2){
		type = args[2].toString();
	}
	return type;
}


private int getPraseMarkKeyIndex(String methodRemark) {
	int index=0;
	Object args[]= methodRemark.split(",");
	if(args.length>1){
		 index =Integer.parseInt(args[1].toString())-1;
	}
	return index;
}


// 获取方法的中文备注____用于记录用户的操作日志描述
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);
				methode = methodCache.remark();
				break;
			}
		}
	}
	return methode;
}

}

config=========

在方法中
@MethodLog(methodRemark=“自定义信息,第一个参数,type(object or string ),key字段名(如果type=object 是object中的keyValue)”)

=link class======
package javacommon.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.aop.ThrowsAdvice;

/import com.alibaba.fastjson.JSON;
import com.vipshop.microscope.common.trace.Category;
import com.vipshop.microscope.trace.Tracer;
/

/**
*

  • @ClassName: ExceptionAdvisor
  • @Description: 负责异常处理的Advice 使用Throw通知类型来实现Advice
  • @author wentao.zhang

*/
public class ExceptionAdvisor implements ThrowsAdvice{

/**异常拦截列表*/
private List<String> exceptionList = null;

/**产生日期*/
private static final String KEY_TIMESTAMP = "timestamp";
/**错误信息*/
private static final String KEY_MESSAGE = "message";
/**完整类名信息*/
private static final String KEY_FQCN = "fullyQualifiedClassName";
/**方法名称*/
private static final String KEY_METHOD = "method";
/**包名称*/
private static final String KEY_PACKAGE = "package";
/**类名*/
private static final String KEY_CLASS_NAME = "className";
/**异常类*/
private static final String KEY_EXCEPTION_CLASS = "exceptionClass";

private Map<String, String> hostInfo = new ConcurrentHashMap<String, String>();    

/**
 * 初始化时调用
 */
public void init(){
	//Tracer.cleanContext();
}

/**
 * 重写afterThrowing()方法
 * @param method 执行方法
 * @param args 执行参数
 * @param target 执行实体
 * @param e 父类
 * @throws Throwable 异常
 */
public void afterThrowing(Method method, Object[] args, Object target,
		RuntimeException e) throws Throwable {

	//Tracer.clientSend("AOP-Exception", Category.Method);
	Map<String, Object> resultMap = null;
	//在这里判断异常,根据异常拦截列表对异常进行拦截
	if(e.getClass().getSimpleName() != null){
		
		if(exceptionList.contains(e.getClass().getSimpleName())){
			
			resultMap = new ConcurrentHashMap<String, Object>();
			resultMap.putAll(hostInfo);
			resultMap.put(KEY_TIMESTAMP,new Date(System.currentTimeMillis()));
			setupClass(resultMap,target.getClass().getName());

			resultMap.put(KEY_METHOD,method.getName());
			resultMap.put(KEY_MESSAGE,e.getMessage());
			resultMap.put(KEY_EXCEPTION_CLASS,e.getClass().getName());
			//JSON.toJSONString(resultMap,true);
        	//Tracer.record(e,JSON.toJSONString(resultMap,false));
			//System.out.println(JSON.toJSONString(resultMap,true));
		}
	}
	
	//Tracer.clientReceive();
}

/**
 * 获取类信息:完整类名称信息、类名称、包
 */
private Map<String, Object> setupClass(Map<String, Object> resultMap,
		final String className) {

	if (className != null && className.trim().length() > 0) {
		resultMap.put(KEY_FQCN, className);
		List<Object> packageComponents = new ArrayList<Object>();
		String[] packageAndClassName = className.split("\\.");
		packageComponents.addAll(Arrays.asList(packageAndClassName));
		if (className.lastIndexOf(".") != -1) {
			resultMap.put(KEY_PACKAGE,
					className.substring(0, className.lastIndexOf(".")));
		}
		resultMap.put(KEY_CLASS_NAME,packageAndClassName[packageAndClassName.length - 1]);
	}

	return resultMap;
}

public List<String> getExceptionList() {
	return exceptionList;
}

public void setExceptionList(List<String> exceptionList) {
	this.exceptionList = exceptionList;
}

}

package javacommon.util;

import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
/**
 * @author Owner Jan 18, 2010 2:37:10 PM 处理DAO层的异常 struts2 com.beckham.aop
 *         ExceptionLog.java
 */
public class ExceptionLog implements ThrowsAdvice {
	/**
	 * Owner 
	 * 参数解释 Method method 执行的方法 
	 * Object[] args 方法参数
	 *  Object target 代理的目标对象
	 * Throwable throwable 产生的异常 
	 * Jan 18, 2010 3:21:46 PM
	 */
	public void afterThrowing(Method method, Object[] args, Object target,
			RuntimeException  throwable) {
		System.out.println("产生异常的方法名称:  " + method.getName());
		
		for(Object o:args){
			System.out.println("方法的参数:   " + o.toString());
		}
		
		System.out.println("代理对象:   " + target.getClass().getName());
		System.out.println("抛出的异常:    " + throwable.getMessage()+">>>>>>>"
				+ throwable.getCause());
		System.out.println("异常详细信息:   "+throwable.fillInStackTrace());
	}

}

==================
package javacommon.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.interceptor.annotations.Before;
@Aspect
@Component
public class logAdvisor {

public void beforeMethod(JoinPoint joinPoint){
Object jo[]= joinPoint.getArgs();
for(int v=0;v<jo.length;v++){

	   System.out.print("find args"+jo[v]+"\n\r");
   }
   System.out.print("end log");

}

}

=====================================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值