AOP切面-自定义注解

  |   0 评论   |   0 浏览

spring配置

<!-- 配置开启@Aspect支持 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

自定义注解

/**
 * 自定义注解-异步监听
 */
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface AsyncMonitor {
	String name();
}

调用的方法

	/**
	 * 新卡办理
	 */
	@Async
	@AsyncMonitor(name = "新卡办理")
	public Comprehensive newCard(Comprehensive comprehensive){
	
		//定义结果对象
		Comprehensive result = new Comprehensive();
		
		//业务处理...
		result.setNewCard(num);
		
		//返回结果
		return result;
	}

AOP切面类

@Component
@Aspect
public class ComprehensiveAop {
	
	/**
	 * 日志对象
	 */
	protected static Logger logger = LoggerFactory.getLogger(ComprehensiveAop.class);
	
	@Around("@annotation(com.thinkgem.jeesite.modules.comprehensive.aop.annotation.AsyncMonitor)")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();		
		Object res = joinPoint.proceed();
		long costTime = System.currentTimeMillis() - startTime;	
		
		//获取类的字节码对象,通过字节码对象获取方法信息
		Class<?> targetCls=joinPoint.getTarget().getClass();
		
		//获取方法签名(通过此签名获取目标方法信息)
		MethodSignature ms=(MethodSignature)joinPoint.getSignature();
		
		//获取目标方法上的注解指定的操作名称
		Method targetMethod=targetCls.getDeclaredMethod(ms.getName(),ms.getParameterTypes());
		AsyncMonitor asyncMonitor=targetMethod.getAnnotation(AsyncMonitor.class);
		String name = asyncMonitor.name();
		
		//记录执行请求耗时
		logger.info("=======> "+name+ " finished ! Cost : " + costTime + " ms.");	
		return res;
	}	
	
	@Before("@annotation(com.thinkgem.jeesite.modules.comprehensive.aop.annotation.AsyncMonitor)")
	public void before(JoinPoint joinPoint){
		String classname=joinPoint.getTarget().getClass().getName();
		String methodname = joinPoint.getSignature().getName();
		//方法执行前处理
		System.out.println("执行前");
	}
	
	@AfterReturning(returning="result", pointcut="@annotation(com.thinkgem.jeesite.modules.comprehensive.aop.annotation.AsyncMonitor)")
	public void afterReturning(JoinPoint joinPoint,Object result){
		String classname=joinPoint.getTarget().getClass().getName();
		String methodname = joinPoint.getSignature().getName();
		//方法执行后-处理返回结果
		System.out.println(result);
	}
	
	@AfterThrowing(throwing="a",pointcut="@annotation(com.thinkgem.jeesite.modules.comprehensive.aop.annotation.AsyncMonitor)")
	public void afterThrowing(JoinPoint joinPoint,Throwable a){
		String classname=joinPoint.getTarget().getClass().getName();
		String methodname = joinPoint.getSignature().getName();
		//方法执行异常-处理
		System.out.println(a);
	}
}