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

Spring3 AOP配置异常。执行时间记录

2013-01-09 15:43 1036 查看

第一种配置方法:使用@AspectJ标签

在配置文件中添加<aop:aspectj-autoproxy/>注解

创建一个Java文件,使用@Aspect注解修饰该类

创建一个方法,使用@Before、@After、@Around等进行修饰,在注解中写上切入点的表达式(写法参考:"execution (* com.myapp.service.impl.*.*(..))")

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

import org.springframework.stereotype.Component;

/**

* 基于注解的AOP日志示例

* @author

*/

@Component

@Aspect

public class AopLog {

@Pointcut("execution (* com.iflysse.school.services.impl.*.*(..))")

public void pointcut(){}

//方法执行前调用

@Before(value="pointcut()")

public void before() {

System.out.println("before");

}

@After (value="pointcut()")

public void after(){

System.out.println("after");

}

//方法执行的前后调用

@Around("pointcut()")

public Object around(ProceedingJoinPoint point) throws Throwable{

long time=System.currentTimeMillis();

Object retVal=point.proceed()l

System.out.println("方法运行时间:"+time-System.currentTimeMillis());

return object;

}

//@AfterThrowing(pointcut="pointcut()")

如果使用该种写法则无法给doThrowing添加Throwable ex

参数,如没有该参数我们无法获悉程序运行的错误:error at ::0 formal unbound in pointcutd

故可修改成为如下:

@AfterThrowint(pointcut="pointcut()" ,throwing="ex")

public void doThrowing(JoinPoint jp,Throwable ex){

System.out.println("可以记录程序运行时候抛出的异常信息");

}

}

第二种配置方法:使用spring配置文件

1. 依旧使用上面那个类 但是要去掉类中的注解,使其成为一个普通的java类。

2.修改applicationContext.xml的配置文件

3.添加如下内容

<bean id="aopLog" class="com.iflysse.school.aop.AopLog"></bean>

<aop:config>

<aop:aspect ref="aopLog">

<aop:pointcut id="pointcutAop" expression="execution (* com.myapp.service.impl.*.*(..))"/ />

<aop:around method="around" pointcut-ref="pointcutAop">

<aop:afterThrowing method="doThrowing" pointcut-ref="pointcutAop" throwing="ex" />

</aop:aspect>

</aop:config>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  aop 日志 log4j