实现SpringAOP--基于 @AspectJ 注解

Spring3 为 AOP 的实现提供了一套 Annotation 注解,如下:

  • @AspectJ:用于定义一个切面。
  • @Pointcut:用于定义一个切入点,切入点的名称由一个方面名称定义。
  • @Before:用于定义一个前置通知。
  • @AfterReturning:用于定义一个后置通知。
  • @AfterThrowing:用于定义一个异常通知。
  • @Around:用于定义一个环绕通知。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//日志切面
@Aspect
public class AllLogAdviceByAnnotation
{
private Logger logger=Logger.getLogger(AllLogAdviceByAnnotation.class);

/**
*使用 @Pointcut 注解定义一个切入点,切入点的名字为 allMethod(),
*切入点的正则表达式 execution(* com.shw.biz.UserBiz.*(..))
*含义是对 com.shw.biz.UserBiz 中的所有方法进行拦截
**/
@Pointcut("execution(* com.shw.biz.UserBiz.*(..))")
//定义切入点名字,切入点是一个方法
private void allMethod(){}

//定义前置通知
@Before("allMethod()")
public void myBeforeAdvice(JoinPoint joinpoint)
{
//获取被调用的类名
String targetClassName=joinpoint.getTarget().getClass().getName();
//获取被调用的方法名
String targetMethodName=joinpoint.getSignature().getName();
//日志格式字符串
String logInfoText="前置通知:"+ targetClassName + "类的" + targetMethodName + " 方法开始执行 ";
//将日志信息写入配置文件中
logger.info(logInfoText);
}

//定义后置通知
@AfterReturning("allMethod()")
public void myAfterReturnAdvice(JoinPoint joinpoint)
{
//获取被调用的类名
String targetClassName=joinpoint.getTarget().getClass().getName();
//获取被调用的方法名
String targetMethodName=joinpoint.getSignature().getName();
//日志格式字符串
String logInfoText="后置通知:"+ targetClassName + "类的" + targetMethodName + " 方法开始执行 ";
//将日志信息写入配置文件中
logger.info(logInfoText);
}

//定义异常通知
@AfterThrowing(pointcut="allMethod()",throwing="e")
public void myThrowingAdvice(JoinPoint joinpoint,Exception e)
{
//获取被调用的类名
String targetClassName=joinpoint.getTarget().getClass().getName();
//获取被调用的方法名
String targetMethodName=joinpoint.getSignature().getName();
//日志格式字符串
String logInfoText="异常通知:执行"+ targetClassName + "类的" + targetMethodName + " 方法时发生异常 ";
//将日志信息写入配置文件中
logger.info(logInfoText);
}

//定义环绕通知
@Around("allMethod()")
public void myAroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable
{
long beginTime=System.currentTimeMillis();
joinpoint.proceed();
long endTime=System.currentTimeMillis();
//获取被调用的方法名
String targetMethodName=joinpoint.getSignature().getName();
//日志格式字符串
String logInfoText="环绕通知:"+ targetMethodName + " 方法调用前时间" + beginTime + "毫秒," + "调用后时间" + endTime + "毫秒";
//将日志信息写入配置文件中
logger.info(logInfoText);
}

为了让 @AspectJ 的注解能正常工作,需要在配置文件的 <beans> 标记中导入 AOP 命名空间及其配套的 schemaLocation 。还需要开启基于 @AspectJ 切面的注解处理器,并将日志通知 AllLogAdviceByAnnotation 交给 Spring 容器管理。

1
2
3
4
<!-- 开启基于 @AspectJ 切面的注解处理器 -->
<aop:aspectj-autoproxy />
<!-- 将日志通知 AllLogAdviceByAnnotation 交给 Spring 容器管理 -->
<bean class="com.shw.aop.AllLogAdviceByAnnotation" />