AOP中的@Aspect用法,用于监控程序的执行方法

来源:互联网 发布:topgun软件下载 编辑:程序博客网 时间:2024/06/05 08:46

转自:http://herryhaixiao.iteye.com/blog/1812555

Spring使用的AOP注解分为三个层次:

前提条件是在xml中放开了<aop:aspectj-autoproxy proxy-target-class="true"/><!-- 开启切面编程功能 -->

1、@Aspect放在类头上,把这个类作为一个切面。

2、 @Pointcut放在方法头上,定义一个可被别的方法引用的切入点表达式。

3、5种通知。

3.1、@Before,前置通知,放在方法头上。

3.2、@After,后置【finally】通知,放在方法头上。

3.3、@AfterReturning,后置【try】通知,放在方法头上,使用returning来引用方法返回值。

3.4、@AfterThrowing,后置【catch】通知,放在方法头上,使用throwing来引用抛出的异常。

3.5、@Around,环绕通知,放在方法头上,这个方法要决定真实的方法是否执行,而且必须有返回值。

@Component@Aspectpublic class LogAspect {/** * 定义Pointcut,Pointcut的名称 就是simplePointcut,此方法不能有返回值,该方法只是一个标示 */@Pointcut("execution(public * com.service.impl..*.*(..))")public void recordLog() {}@AfterReturning(pointcut = "recordLog()")public void simpleAdvice() {LogUtil.info("AOP后处理成功 ");}@Around("recordLog()")public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {LogUtil.info("正常运行");return jp.proceed();}@Before("recordLog()")public void before(JoinPoint jp) {String className = jp.getThis().toString();String methodName = jp.getSignature().getName(); // 获得方法名LogUtil.info("位于:" + className + "调用" + methodName + "()方法-开始!");Object[] args = jp.getArgs(); // 获得参数列表if (args.length <= 0) {LogUtil.info("====" + methodName + "方法没有参数");} else {for (int i = 0; i < args.length; i++) {LogUtil.info("====参数  " + (i + 1) + ":" + args[i]);}}LogUtil.info("=====================================");}@AfterThrowing("recordLog()")public void catchInfo() {LogUtil.info("异常信息");}@After("recordLog()")public void after(JoinPoint jp) {LogUtil.info("" + jp.getSignature().getName() + "()方法-结束!");LogUtil.info("=====================================");}}

细节介绍:

@AspectJ的详细用法 
在spring AOP中目前只有执行方法这一个连接点,Spring AOP支持的AspectJ切入点指示符如下:

一些常见的切入点的例子 
execution(public * * (. .)) 任意公共方法被执行时,执行切入点函数。 
execution( * set* (. .)) 任何以一个“set”开始的方法被执行时,执行切入点函数。 
execution( * com.demo.service.AccountService.* (. .)) 当接口AccountService 中的任意方法被执行时,执行切入点函数。 
execution( * com.demo.service.. (. .)) 当service 包中的任意方法被执行时,执行切入点函数。 within(com.demo.service.) 在service 包里的任意连接点。 within(com.demo.service. .) 在service 包或子包的任意连接点。 
this(com.demo.service.AccountService) 实现了AccountService 接口的代理对象的任意连接点。 
target(com.demo.service.AccountService) 实现了AccountService 接口的目标对象的任意连接点。 
args(Java.io.Serializable) 任何一个只接受一个参数,且在运行时传入参数实现了 Serializable 接口的连接点 
增强的方式: 
@Before:方法前执行 
@AfterReturning:运行方法后执行 
@AfterThrowing:Throw后执行 
@After:无论方法以何种方式结束,都会执行(类似于finally) 
@Around:环绕执行


0 0