1 package aop;
2
3 import java.util.Arrays;
4
5 import org.apache.log4j.Logger;
6 import org.aspectj.lang.JoinPoint;
7 import org.aspectj.lang.ProceedingJoinPoint;
8 import org.aspectj.lang.annotation.After;
9 import org.aspectj.lang.annotation.AfterReturning;
10 import org.aspectj.lang.annotation.AfterThrowing;
11 import org.aspectj.lang.annotation.Around;
12 import org.aspectj.lang.annotation.Aspect;
13 import org.aspectj.lang.annotation.Before;
14 /**
15 * 增强方法
16 * @author 尹涛
17 *
18 */
19 @Aspect
20 public class ErroorLogger {
21 private static final Logger log=Logger.getLogger(ErroorLogger.class);
22 /**
23 * 定义前置增强方法(execution为模糊匹配sercice.impl包下的所有类的所有方法)
24 */
25 @Before("execution(* sercice.impl.*.*(..))")
26 public void before(JoinPoint jp){
27 log.info("前置增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs()));
28 }
29 /**
30 * 后置增强方法(execution为模糊匹配sercice.impl包下的所有类的所有方法)
31 */
32 @AfterReturning(pointcut="execution(* sercice.impl.*.*(..))",returning="retutnValue")
33 public void afterReturning(JoinPoint jp,Object retutnValue){
34 log.info("后置增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs())+",返回值是"+retutnValue);
35 }
36 /**
37 * 异常增强(execution为模糊匹配sercice.impl包下的所有类的所有方法)
38 */
39 @AfterThrowing(pointcut="execution(* sercice.impl.*.*(..))",throwing="e")
40 public void afterThrowing(JoinPoint jp,NullPointerException e){
41 log.info("异常处理增强,"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,发生异常"+e);
42 }
43 /**
44 * 环绕增强(execution为模糊匹配sercice.impl包下的所有类的所有方法)
45 * @return
46 */
47 @Around("execution(* sercice.impl.*.*(..))")
48 public Object around(ProceedingJoinPoint jp){
49 Object result=null;
50 log.info("环绕强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs()));
51 try {
52 result=jp.proceed();
53 log.info("环绕增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs())+",返回值是"+result);
54 } catch (Throwable e) {
55 log.info(jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法异常"+e);
56 }
57 return result;
58 }
59 /**
60 * 最终增强(execution为模糊匹配sercice.impl包下的所有类的所有方法)
61 */
62 @After("execution(* sercice.impl.*.*(..))")
63 public void after(JoinPoint jp){
64 log.info("最终增强"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法执行结束");
65 }
66 }
配置文件
<bean id="before" class="aop.ErroorLogger"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>