aop_aspect_写给自己看的

@Aspect 面向切面编程
<aop:aspectj-autoproxy/>
<aop:aspectj-autoproxy poxy-target-class="true"/>  true代表cglib 默认值为false即使用jdk代理 不过如果目标类没有声明接口  会自动使用cglib

先定义一个切点
@Pointcut("execution(* com.qbsea.myspringboota.modules.*.service..*(..))")
public void excuteService() {

}
再给这个切点指定具体的业务逻辑的处理 比如这里对异常的log

@Before 前置通知
@AfterReturning 返回通知
@After 后置通知


一个例子代码

import java.io.PrintWriter;
import java.io.StringWriter;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;

@Aspect
@Component
public class AspectServiceException {
	public static org.slf4j.Logger logger = LoggerFactory.getLogger(AspectServiceException.class);

	@Pointcut("execution(* com.qbsea.myspringboota.modules.*.service..*(..))")
	public void excuteService() {

	}

	// 对异常的记录
	@AfterThrowing(value = "excuteService()", throwing = "ex")
	public void afterThorwingMethod(JoinPoint thisJoinPoint, Exception ex) {
		String methodName = thisJoinPoint.getSignature().getName();// 目标方法
		String className = thisJoinPoint.getTarget().getClass().getName();// 目标类
		Object[] objArray = thisJoinPoint.getArgs();// 参数
		String objArrayJson = new Gson().toJson(objArray);
		String exceptinstr = sysOutExcepMsg(ex);
		logger.info("[class=" + className + "][method=" + methodName + "][param=" + objArrayJson + "][exception="
				+ exceptinstr + "]");
	}

	@Before("execution(* com.qcc.beans.aop.*.*(..))")
	public void beforeMethod(JoinPoint jp) {
		String methodName = jp.getSignature().getName();
		System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
	}

	@AfterReturning(value = "execution(* com.qcc.beans.aop.*.*(..))", returning = "result")
	public void afterReturningMethod(JoinPoint jp, Object result) {
		String methodName = jp.getSignature().getName();
		System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
	}

	@After("execution(* com.qcc.beans.aop.*.*(..))")
	public void afterMethod(JoinPoint jp) {
		System.out.println("【后置通知】this is a afterMethod advice...");
	}

	// 得到异常信息
	private static String sysOutExcepMsg(java.lang.Exception e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw, true));
		String str = sw.toString();
		return str;
	}
}

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/81566056